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 :
public bool PollForFile(FileInfo file)
{
bool fileReady = false;
while (!fileReady)
{
try
{
//Check if file is not in use ..if it is in use then it cannot be opened,so exception will be thrown.
using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fileReady = true;
break;
}
}
catch (IOException)
{
//File isn't ready yet, so we need to keep on waiting until it is.
fileReady = false;
}
//We'll want to wait a bit between polls, if the file isn't ready.
if (!fileReady)
{
Thread.Sleep(1000);
}
}
return fileReady;
}