Search code examples
c#directoryfilenotfoundexception

Why do I get a FileNotFoundException when the file obviously exists?


I have a piece of C# code in which I try to list some files from a directory. When listing the files I get a FileNotFoundException (which is not caught yet), but I don't understand why...

    try
    {
        String[] files = Directory.GetFiles(directory);
        FileInfo fi = new FileInfo(file);
        long size = fi.Length;
    }
    catch (UnauthorizedAccessException)
    {
        Console.WriteLine("Cannot enumerate files from " + directory);
    }

The value for directory is

D:\_temporary_files\2024_temporary_files_temporary_file-2024-07-21_-_author_unknown_length_unknown_size_unknown\2024_temporary_files_temporary_file-2024-07-21_-_author_unknown_length_unknown_size_unknown

The file which gives me the FileNotFoundException is

D:\_temporary_files\2024_temporary_files_temporary_file-2024-07-21_-_author_unknown_length_unknown_size_unknown\2024_temporary_files_temporary_file-2024-07-21_-_author_unknown_length_unknown_size_unknown\2024_temporary_files_temporary_file-2024-07-21_-_17-11-00-0001.dat

I tried to recursively list files in directories, starting from the root D:, but got a FileNotFoundException when I hit the above file/directory.

I suspect it may have something to do with the length of path/filename, yet I can see, list, edit the file perfectly fine in Windows (10), notepad, other editors, other file explorers, whatever.

Since all other software tools seem to have no problem handling this file, why am I getting this exception in C#?

Thanks!

Edit: in my haste I left out the piece of code which generates the FileNotFoundException - getting the length of the file throws the error.


Solution

  • As stated in Maximum Path Length Limitation:

    In the Windows API [...], the maximum length for a path is MAX_PATH, which is defined as 260 characters.

    Your path including the file name has a length of 270 characters.

    You might still be able to see the file in the Windows Explorer, but some file operations might fail.

    While this limit has been removed in Windows 10 version 1607, some APIs are still limited by the historical limit.

    See also: