[Sample of Mar 12th] Check whether a file is in use or not
![]() |
![]() |
|
![]() |
![]() |
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:
- https://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/76d63016-3864-4020-849a-01a82276493d/
- https://social.msdn.microsoft.com/forums/en-us/netfxbcl/thread/a539cbdc-5f42-4f09-9e04-860845aa049d/
- https://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/4e3a6014-4cd7-4d38-ba87-ccf9ce28b3c5/
- https://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/f225e48c-0321-49a3-9134-53f409dee5d9/
- https://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/e99a7cea-43d3-49b1-82bc-5669e0b9d052
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 https://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;
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
Comments
- Anonymous
March 12, 2012
Doesn't using FileMode.OpenOrCreate actually create the file when you pass a filename that doesn't exist?