OK, can anyone explain why I can't check explicitly if I can lock a file before reading from it (i.e., check that no-one else is locking the file before trying to read from it). I'm using the marvellous FileSystemWatcher to wait for files being created in a directory before triggering a job - fine but there doesn't seem to be any easy way to check is a file is 'readable' before starting to read... Right now my way of doing this task is to attempt to read - and place a Read lock - on the file using the FileStream and catch the error it throws when the file is locked by another process...like so...but this really doesn't feel right. I balk at the idea of using exceptions (which are also REALLY slow) for this kind of task...why doesn't FileStream.CanRead check for locks BEFORE opening the file???
private static int m_ReadAttempts = 0;
private string ReadFileFromDisk(string filePath)
{
try
{
if(!File.Exists(filePath))
{
MessageBox.Show("Sorry, but the file specified " + Environment.NewLine + filePath + Environment.NewLine + "Cannot be found");
return string.Empty;
}
using(FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read,FileShare.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
string tmpStr = sr.ReadToEnd();
sr.Close();
m_ReadAttempts =0;
return tmpStr;
}
}
}
catch(IOException ex)
{
if(m_ReadAttempts < 10)
{
Thread.Sleep(500);
m_ReadAttempts++;
return ReadFileFromDisk(filePath);
}
else
{
throw ex;
}
}
}
© 2025 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.