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

 

Homepage image
Sample of the Day RSS Feed

Sample Download: https://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 https://1code.codeplex.com/.

 

Running the Sample

image

 

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; 
    try 
    { 
        fs = 
             File.Open(filename, FileMode.OpenOrCreate, 
             FileAccess.ReadWrite, FileShare.None); 
    } 
    catch (IOException ) 
    { 
        locked = true; 
    } 
    finally 
    { 
        if (fs != null) 
        { 
            fs.Close(); 
        } 
    } 
    return locked; 
} 

 

More Information

MSDN: FileStream Class
https://msdn.microsoft.com/en-us/library/system.io.filestream.aspx
 
MSDN: FileAccess Enumeration
https://msdn.microsoft.com/en-us/library/4z36sx0f.aspx
 
MSDN: File Class
https://msdn.microsoft.com/en-us/library/system.io.file.aspx