How to know if a folder of file is being used by another process?
I know there are tens of questions already about "the file being used by another process". But they all have the problem of trying to read a file or write to a file that is already being used by another process. I just want to check to see if a file is being used by anot开发者_如何学Cher process (no IO action after that). I didn't find the answer elsewhere. So, how can I know if a file or folder is being used by another process in C#?
As you describe in the question the only way is to try to open the file first to see if it used by another process.
You can use this method I implemented sometime ago, the idea is if the file exists then try to open the file as open write, and so if failed then the file maybe is used by another process:
public static bool IsFileInUse(string fileFullPath, bool throwIfNotExists)
{
if (System.IO.File.Exists(fileFullPath))
{
try
{
//if this does not throw exception then the file is not use by another program
using (FileStream fileStream = File.OpenWrite(fileFullPath))
{
if (fileStream == null)
return true;
}
return false;
}
catch
{
return true;
}
}
else if (!throwIfNotExists)
{
return true;
}
else
{
throw new FileNotFoundException("Specified path is not exsists", fileFullPath);
}
}
This post might help:
How to check for file lock?
精彩评论