Do you want a faster File.Exists / FileInfo.Exists / Directory.Exists ? I do !


Sometimes you need to check the existence of a file. Nothing is easier with the .Net framework which provide a property named Exists on FileInfo class.

But it can be quite long, especially when the file is on a network drive. If so you’ll have to wait for a time-out to know that the file is not reachable.

This was too slow for me so I coded this little utility which performs the same but with a customizable TimeOut. As it may interest you, here it is:
[csharp]private static bool VerifyFileExists(Uri uri, int timeout)
var task = new Task<bool>(() =>
var fi = new FileInfo(uri.LocalPath);
return fi.Exists;
return task.Wait(timeout) && task.Result;

Enjoy !


4 Responses

  1. Jacob Reimers

    24/08/2011 17 h 15 min

    In effect you are opting to fail instead of wait for the drive to respond. If the drive is powered down by the power options then you risk the method returning false and you could end up overwriting an existing folder. Wouldn’t it be better to push the whole IO task to a background thread as a single unit of work?

    • jmix90

      24/08/2011 21 h 47 min

      Thank you for your comment.

      It could be done but sometimes you need to have the information immediately(from an user point of view). In this case you can\’t do this as a background task.

      This a compromise between speed and \”the truth\”. Don\’t you use It if you want to be sure 100% …

Comments are closed.