16

We have some basic C# logic that iterates over a directory and returns the folders and files within. When run against a network share (\\server\share\folder) that is inaccessible or invalid, the code seems to 'hang' for about 30 seconds before returning back from the call.

I'd like to end up with a method that will attempt to get folders and files from the given path, but without the timeout period. In other words, to reduce or eliminate the timeout altogether.

I've tried something as simple as validating the existence of the directory ahead of time thinking that an 'unavailable' network drive would quickly return false, but that did not work as expected.

System.IO.Directory.Exists(path) //hangs 

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); //hangs

Any suggestions on what may help me achieve an efficient (and hopefully managed) solution?

4 Answers4

27

You can use this code:

var task = new Task<bool>(() => { var fi = new FileInfo(uri.LocalPath); return fi.Exists; });
task.Start();

return task.Wait(100) && task.Result;
Jonathan ANTOINE
  • 9,021
  • 1
  • 23
  • 33
  • 6
    +1 from me, this is great for files but using this to answer the original question is useless. To answer the question, try replacing `new FileInfo(uri.LocalPath)` with `new DirectoryInfo(strPath)` to check directories instead of files. – Arvo Bowen Nov 06 '15 at 21:06
  • 2
    *** this should be the answer *** OP pls chng – Leo Gurdian Nov 07 '17 at 19:53
7

Place it on its own thread, if it doesn't come back in a certain amount of time, move on.

Al Katawazi
  • 7,192
  • 6
  • 26
  • 39
1

Perhaps you could try pinging the server first, and only ask for the directory info if you get a response?

mqp
  • 70,359
  • 14
  • 95
  • 123
  • I have used this successfully for walking our network of machines, looking for software. However, it may not be feasible to parse out the server from the UNC path. – John Gietzen Apr 07 '09 at 16:49
0

See...

Faster DirectoryExists function?

...for a way of setting the execution time for Directory.Exists

Community
  • 1
  • 1