tags:

views:

156

answers:

4

Can anyone please tell me if there is a way to find if a file is already open or not?

+7  A: 
protected virtual bool IsFileinUse(FileInfo file)
{
     FileStream stream = null;

     try
     {
         stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
     }
     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;
     }
     finally
     {
         if (stream != null)
         stream.Close();
     }
     return false; 
}
Pranay Rana
If the process doesn't have write access to the file this will produce a misleading result (the open will fail, but not necessarily because a handle exists.) Opening for Read access would be less error-prone.
hemp
Amazing that most languages don't have a method to test file is open. We used to use the same type of method under C++ in OS/2. i.e. try to open the file exclusive. It works well enough, but I've never thought it elegant.
Matt H
It's not a language feature, it's an OS feature. There just doesn't exist a simple API (in Windows) to query for that information. It is possible to get, but it's low-level and there are a lot of parameters that would have to be specified to know what was meant by "open".
hemp
+2  A: 

As @pranay_stacker, but we need to make sure we close our file handle:

public bool IsFileInUse(string path)
{
  if (string.IsNullOrEmpty(path))
    throw new ArgumentException("'path' cannot be null or empty.", "path");

  try {
    using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { }
  } catch (IOException) {
    return true;
  }

  return false;
}
Matthew Abbott
A: 

If you mean that you want to check if a file is open before you try to open it, then no. (At least not without going low level and examine every file handle that is open in the system.)

Besides, the information would be old when you get it. Even if the test would return that the file is not open, it could have been opened before you have a chance to use the return value.

So, the proper way to handle the situation is to try to open the file, and handle any error than may occur.

Guffa
A: 

Agreed. I would create a designated class which wraps the open file logic or at least the test (IsFileAvailable). This will allow you to place the exception management with a class specifically responsible and make it reusable. You may even apply further logic, such as testing the file size to see if the file is being written to etc, to give a more detailed response. It will also make your consuming code much cleaner.

NoelAdy