Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file is open [duplicate]

Tags:

Is there a way to find if a file is already open or not?

like image 442
Md. Rashim Uddin Avatar asked Jun 07 '10 06:06

Md. Rashim Uddin


2 Answers

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; 
}
like image 129
Pranay Rana Avatar answered Oct 12 '22 22:10

Pranay Rana


As @pranay rana, 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;
}
like image 35
Matthew Abbott Avatar answered Oct 12 '22 22:10

Matthew Abbott