How do I properly open a file for deletion?

Viewed 1533

I thought this is a completely trivial task but it gave me some headache. I would like to open a file to ensure I got exclusive access, test for certain conditions, then delete it.

Right now I'm using a 99% approach:

FileStream s = null;
try {
    s = new FileStream (
        path,
        FileMode.Open,
        FileAccess.ReadWrite,
        FileShare.None);
    // some stuff about the file is checked here
    s.Dispose ();
    // hope the file is not accessed by someone else...
    File.Delete (path);
    return true;
}
catch (IOException) {
    if (s !=null) s.Dispose ();
    return false;
}

This usually works, but I figured there'd be a better way that avoids the edge condition.

Opening the file with a DeleteOnClose flag does not work because said check (which occurs after opening with the deletion flag already set) might indicate that the file should not be deleted.

3 Answers
Related