如何正确打开文件进行删除?

maf*_*afu 10 .net c# file delete-file

我认为这是一个完全无足轻重的任务,但它给了我一些头痛.我想打开一个文件以确保我获得独占访问权限,测试某些条件,然后将其删除.

现在我正在使用99%的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

这通常有效,但我认为有一种更好的方法可以避免边缘条件.

使用DeleteOnClose标志打开文件不起作用,因为所述检查(在打开并且已经设置了删除标志后发生)可能表示不应删除该文件.

Sim*_*ier 7

像这样的东西:

    using (FileStream file = new FileStream(path,
       FileMode.Open,
       FileAccess.ReadWrite,
       FileShare.Delete))
    {
        // you can read the file here and check your stuff
        File.Delete(path);
    }
Run Code Online (Sandbox Code Playgroud)

PS:注意'using'关键字.它允许您在处理Dispose调用时拥有更清晰的代码.