Sample Download: http://code.msdn.microsoft.com/CSCheckFileInUse-1974c9a1
Today’s code sample demonstrates a topic asked by lots of developers in MSDN forums: How to check whether a file is in use or not programmatically. There are tens of forum threads discussing this scenario, so we decided to create a code sample to ease the typical programming task.
Some example forum threads discussing how to check whether a file is in use or not:
The sample was written by the Microsoft engineer: Ajay Pathak.
You can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.
The following function checks whether a file is in use or not.
/// This function checks whether the file is in use or not.
/// <param name="filename">File Name</param>
/// <returns>Return True if file in use else false</returns>
public static bool IsFileInUse(string filename)
bool locked = false;
FileStream fs = null;
catch (IOException )
locked = true;
if (fs != null)
MSDN: FileStream Class http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx MSDN: FileAccess Enumeration http://msdn.microsoft.com/en-us/library/4z36sx0f.aspx MSDN: File Class http://msdn.microsoft.com/en-us/library/system.io.file.aspx
Doesn't using FileMode.OpenOrCreate actually create the file when you pass a filename that doesn't exist?