我原以为这是一个非常简单的任务,但它让我头痛不已。我想打开一个文件以确保我获得了排他性访问权限,测试某些条件,然后将其删除。
现在我正在使用一种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;
}
通常这样做是可行的,但我认为应该有更好的方法来避免边缘情况。
使用DeleteOnClose标志打开文件并不起作用,因为该检查(在已经设置删除标志后打开)可能会指示不应删除该文件。