by jask2002
27. August 2012 23:11
As the saying goes, Prevention is better than cure. It is always better to check whether a file is in use or not before doing any file operation on it to avoid any unexpected IOException during the runtime.
Exception in question is:
System.IO.IOException: The process cannot access the file 'C:\Inetpub\XXX.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights,…)
at System.IO.FileStream..ctor(String path, FileMode mode)
Here is the simple code to make a file check using static method IsFileInUse
if (FileInUse.IsFileInUse(fileName))
{
status = "File is in use";
}
else
{
status = "File is not in use";
}
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 )
{
//We are capturing IOException
locked = true;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
return locked;
}
You can download the Complete Source code from OneCode site (I’ve recently checked in there) 
|
Has this post helped you? Saved you? If you'd like to show your appreciation. Please buy me a coffee or make a small contribution
toward blog's maintenance(to keep it Ads free )
|
f477bc7f-0fc6-4b15-b6ab-65bca344185d|0|.0
Tags: IOException, File in use, used by another process
.Net | C#