/// /// Uses recursion to check if the passed in filename is already locked by another process /// it will continue to check to see if lock is released so that the caller can access it /// It will currently only ever return true if the file is unlocked but never return false. /// it would be dead easy to add a timer to this to automatically time out after a set period /// unless you are happy for your app to wait until the process is finished. /// /// filename to check/// true or falseprivate static bool IsFileUsedbyAnotherProcess(string filename)
{FileStream fs = null;try {
fs = File.Open(filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
}catch (System.IO.IOException exp)
{string msg = exp.Message;
fs.Close();
fs.Dispose();
IsFileUsedbyAnotherProcess(filename); // recheck access }
fs.Close();
fs.Dispose();return false;
}