Check if file is in use in C#

There is no build-in function in c# to check if a file is in use. You can just try to open file for reading and catch the exception. This is not a 100% safe way because the file could become locked by another thread or process milliseconds after you do the check or it is closed.

Boolean isInUse(String filename)
{
	try
	{
		using (Stream stream = new FileStream(filename, FileMode.Open))
		{
			stream.Close();
			return false;
		}
	}
	catch
	{
		return true;
	}
}
Categories: C# Tags: , , , ,
%d bloggers like this: