[Sample of Mar 12th] Check whether a file is in use or not - Microsoft All-In-One Code Framework - Site Home - MSDN Blogs
Microsoft All-In-One Code Framework - Developers' Pain Killer

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

Rate This
  • Comments 1

 

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

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
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

Leave a Comment
  • Please add 8 and 3 and type the answer here:
  • Post
  • Doesn't using FileMode.OpenOrCreate actually create the file when you pass a filename that doesn't exist?

Page 1 of 1 (1 items)