Click here to Skip to main content
14,921,505 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following code:

DirectoryInfo directoryInfo = new DirectoryInfo( path );
IEnumerable<FileInfo> files = directoryInfo.EnumerateFiles( "*.*", SearchOption.TopDirectoryOnly );
foreach( FileInfo file in files )
    // Do something...

Sometimes, this gives a DirectoryNotFoundException. Since all I am doing in effect is asking .NET to give me a list of subdirectories it finds in a given directory, I don't understand how an immediate enumeration of these can decide one of them cannot be found. It seems illogical.

Can anyone explain what may be going on or at least where I should focus my investigation?

What I have tried:

Although the application is being run simultaneously by a handful of users on a LAN, directories are rarely deleted or renamed and so it is extremely unlikely this error is being caused by another user doing something at exactly the wrong moment.

The only explanation offered on Microsoft's help is that this exception could be caused by an unmapped network drive. All these folders are indeed on a mapped network drive but are all on the same drive. Therefore, if the parent path I use to construct the DirectoryInfo is present then any subfolders should also be accessible.
Updated 6-May-21 0:55am

1 solution

See DirectoryInfo.EnumerateFiles Method (System.IO) | Microsoft Docs[^]. But what you are asking is for the system to EnumerateFiles. I think you should be using DirectoryInfo.EnumerateDirectories Method (System.IO) | Microsoft Docs[^].
Patrick Skelton 7-May-21 4:17am
Thanks for the reply, Richard. I believe I am using the correct function, since I am wanting only files in one specific directory. By adding some logging, I have identified what I believe is a simple failure of the UI layer to be refreshed and therefore the containing path passed into the DirectoryInfo constructor could indeed have vanished from existence. I am now wearing a hat with a 'D' on the front. At least it's Friday.
Richard MacCutchan 7-May-21 5:42am
Sorry, I misread at the point where you said, "asking .NET to give me a list of subdirectories it finds in a given directory".
Patrick Skelton 7-May-21 5:51am
Even my question was confused. I was having a good day. :/
Richard MacCutchan 7-May-21 5:52am
Ha ha, join the club.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900