How to determine if a file is being used by another process?

-------------------------------------------------------
Goto blog home
Visit my new blog dedicated to Internet of Things, Embedded Programming & Automation
-------------------------------------------------------
Here is a utility function written in C#.NET that can be used to determined whether a file is in use by another process. I used it in one of the file routing windows services that I wrote, you can reuse this as needed. The trick is to request exclusive access to the file using 'FileShare.None' enumeration value. The function will throw an exception if the file is already open by another process.

private bool IsFileInUse(FileInfo objFileInfo)
{
FileStream _objFileStream = null;
try
{

if(objFileInfo.Exists)
{
_objFileStream = objFileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);

}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread

return true;
}
finally
{
if (_objFileStream != null)
_objFileStream.Close();
}
//file is not locked
return false;
}

No comments:

Post a Comment