Link to home
Start Free TrialLog in
Avatar of SGyves
SGyves

asked on

C# Determine if a file is being accessed

How can I test to see if a file is being accessed by another process? I want to be sure that the file is not being accessed before I perform an operation on it. And I want to test for this without throwing exceptions.
Avatar of JipFromParis
JipFromParis

Just try this :

FileStream theFile = null;
try
{
    bool gotAccess = true;
    try {theFile = File.OpenFile(theFileName,  FileMode.Open, FileAccess.Read, FileShare.None);}
    catch (Exception) {gotAccess = false;}
    if (gotAccess)
   {
        // Here you've got exclusive access and you can perform the job.
   }
}
finally {if (theFile != null) {theFile.Close();}
Avatar of SGyves

ASKER

What if what  I want to do is Delete the file? It has to be closed. And if I got access....I am presented with the same problem of making sure that the file is closed before I attempt a delete.
Avatar of SGyves

ASKER

I can call Close on teh stream...but there is a period of time that must pass before the stream is actually closed and the file is released.
ASKER CERTIFIED SOLUTION
Avatar of JipFromParis
JipFromParis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SGyves

ASKER

I am making a brute force file deleter. It is all too often that I want to delete a file that I do not need any more...but it is being accessed by another process. So, I tell the program to get all processes using that file...terminate them...and delete the file in question. However, there is a delay between the killing of the process, and the deletion of the file. I need to compensate for that. I would prefer that the program attempt to delete this file until it succeeds, or times out after a certain time.
Avatar of SGyves

ASKER

Ok...got it. I just made a special delete method that returns false if it fails and true if it succeeds. That way  I can loop on it until it returns true.