Alex Rivera | Logout

Deleting files in use

Asked 2012-05-08T18:51:25.183
30

I created a simple program to delete temporary files in C# (for fun, not a major project) and am running into locked files (in use) issues. How do you normally either exclude those files? For reference I am receiving the error:

The process cannot access the file 'ExchangePerflog_8484fa31c65c7a31cfcccd43.dat' because it is being used by another process.

Code:

static void Main(string[] args)
    {
        string folderPath = string.Empty;
        folderPath = System.Environment.GetEnvironmentVariable("temp");
        deleteFilesInDirectory(folderPath);
    }

    public static void deleteFilesInDirectory(string folderPath) 
    {

        try
        {
            var dir = new DirectoryInfo(folderPath);
            dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
            dir.Delete(true);
            MessageBox.Show(folderPath + " has been cleaned.");
        }
        catch (System.IO.IOException ex)
        {
            MessageBox.Show(ex.Message); 
            return;

        } 
    }     
c#
Edit
Report

1 Answer

1

I don't believe there is any way you can know in advance if the file is in use or not. You could try to get an exclusive lock on the file; but then you'd just be trading one exception for another.

If these are files you are opening, see if you can't do a better job of closing them. If it's more complicated than that - you could maintain a 'to delete list' and continue to retry the delete until it is successful (on another thread with a concurrent collection maybe).

I also don't believe there is anyway to forcefully delete an in-use file.

answered 2012-05-08T18:57:43.977

Your Answer