How to detect if a file is in use?

Asked

Viewed 62 times

2

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

1 answer

3

You can use this method to make this check:

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 reply soen.

Edit:

As you do not know the full name of the file use the method Directory.Getfiles, passing a search Pattern, he returns a array of strings with the paths of all files that obey the search Pattern.

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

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

  • I already knew that, but I wanted to test it on a file called "javaw".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.