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 another 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#?
Asked
Active
Viewed 7,589 times
2
-
Possible duplicate of [How to check for file lock?](http://stackoverflow.com/questions/1304/how-to-check-for-file-lock) – Jon Schneider Jan 28 '16 at 19:55
2 Answers
3
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);
}
}

Jalal Said
- 15,906
- 7
- 45
- 68
-
This is a good way, thanks. But the simplest way and almost everybody thinks of it first. I just wanted to see if there is any canonical way to do it in .NET. But thank you so much for helping. – Saeed Neamati Jun 27 '11 at 10:47
-
Well, as I looked into other threads, seems that the only way is to try to open the file in a try catch block, and check the exception type to see if it's locked or not. – Saeed Neamati Jun 27 '11 at 10:53
-
1Though the file might still be in use, just the other process has allowed shared write access. – Chris Chilvers Jun 27 '11 at 11:15
-
@Chris Chilvers: Yes, but the idea is that no exception is thrown "tilling us that the file is being used by another process". However note that the file _maybe_ became in use just after the check and before the actual open file code "in a nanoseconds..". but we reduce the possibilities. – Jalal Said Jun 27 '11 at 11:23