How to detect if a file is in use? [duplicate]

2

I want to detect if a file started by something ( javaw ) in a given directory is in use or not.

    
asked by anonymous 18.09.2015 / 16:51

1 answer

3

You can use this method to do this:

protected virtual bool IsFileInUse(FileInfo file)
{
     FileStream stream = null;

     try
     {
         stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
     }
     catch (IOException)
     {
         //O ficheiro não está disponível porque está a ser utilizado ou não existe.
         return true;
     }
     finally
     {
         if (stream != null)
         stream.Close();
     }
     return false; 
}

Use the method as follows:

FileInfo file = new FileInfo(path);
if(IsFileInUse(file))
{
    //está a ser utilizado
}
else
{
    //não está a ser utilizado
}

Adapted from this SOen's response .

Edit:

Because you do not know the full file name, use the Directory method. GetFiles , by passing a search pattern , it returns an array of strings with the paths of all the files that obey the search pattern .

string[] dirs = Directory.GetFiles(@"oSeuDirectorio", "javaw*");

Then use the IsFileInUse() method for each of the array elements

    
18.09.2015 / 17:25