Poll for a File in Server Path in C#

Sometimes we come across situations where we have to poll for a file availability in a server location.

Simple code to do it is given below:

  1. public bool PollForFile(FileInfo file)  
  2. {  
  3.      bool fileReady = false;  
  4.      while (!fileReady)  
  5.      {  
  6.          try  
  7.          {  
  8.              //Check if file is not in use ..if it is in use then it cannot be opened,so exception will be thrown.  
  9.              using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))  
  10.              {  
  11.                  fileReady = true;  
  12.                  break;  
  13.              }  
  14.          }  
  15.          catch (IOException)  
  16.          {  
  17.              //File isn't ready yet, so we need to keep on waiting until it is.  
  18.              fileReady = false;  
  19.          }  
  20.    
  21.          //We'll want to wait a bit between polls, if the file isn't ready.  
  22.          if (!fileReady)  
  23.          {  
  24.              Thread.Sleep(1000);  
  25.          }  
  26.      }  
  27.      return fileReady;  
  28. }