Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a file is in use?

I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error:

"File in use by another process"

I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling. This is against my religion, so I was wondering if anyone has a better way of doing it?

like image 663
Dawsy Avatar asked May 18 '09 06:05

Dawsy


People also ask

Is there a way to check if a file is in use C#?

try { using (Stream stream = new FileStream("MyFilename. txt", FileMode. Open)) { // File/Stream manipulating code here } } catch { //check here why it failed and ask user to retry if the file is in use. }

What is FileInfo C#?

The FileInfo class is used to deal with file and its operations in C#. It provides properties and methods that are used to create, delete and read file. It uses StreamWriter class to write data to the file. It is a part of System.IO namespace.


2 Answers

You can suffer from a thread race condition on this which there are documented examples of this being used as a security vulnerability. If you check that the file is available, but then try and use it you could throw at that point, which a malicious user could use to force and exploit in your code.

Your best bet is a try catch / finally which tries to get the file handle.

try {    using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))    {         // File/Stream manipulating code here    } } catch {   //check here why it failed and ask user to retry if the file is in use. } 
like image 43
Spence Avatar answered Sep 19 '22 13:09

Spence


Updated NOTE on this solution: Checking with FileAccess.ReadWrite will fail for Read-Only files so the solution has been modified to check with FileAccess.Read.

ORIGINAL: I've used this code for the past several years, and I haven't had any issues with it.

Understand your hesitation about using exceptions, but you can't avoid them all of the time:

protected virtual bool IsFileLocked(FileInfo file) {     try     {         using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))         {             stream.Close();         }     }     catch (IOException)     {         //the file is unavailable because it is:         //still being written to         //or being processed by another thread         //or does not exist (has already been processed)         return true;     }      //file is not locked     return false; } 
like image 152
ChrisW Avatar answered Sep 21 '22 13:09

ChrisW