[Sample of Mar 12th] Check whether a file is in use or not


Homepage image
Sample of the Day RSS Feed

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.

imageYou 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/.


Running the Sample



Using the Code

The following function checks whether a file is in use or not.

/// <summary> 
/// This function checks whether the file is in use or not. 
/// </summary> 
/// <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; 
        fs = 
             File.Open(filename, FileMode.OpenOrCreate, 
             FileAccess.ReadWrite, FileShare.None); 
    catch (IOException ) 
        locked = true; 
        if (fs != null) 
    return locked; 


More Information

MSDN: FileStream Class
MSDN: FileAccess Enumeration
MSDN: File Class

Comments (1)

  1. AlGonzalez says:

    Doesn't using FileMode.OpenOrCreate actually create the file when you pass a filename that doesn't exist?

Skip to main content