【发布时间】:2014-08-25 07:03:48
【问题描述】:
我使用 Directory.Delete(path,true) 方法删除目录。在删除之前,我用这个方法来检查文件夹是否可以删除:
private bool FileCanDelete(string path)
{
try
{
//if this does not throw exception then the file is not use by another program
using (FileStream fileStream = File.OpenWrite(path))
{
if (fileStream == null)
return false;
}
return true;
}
catch (UnauthorizedAccessException uaex)
{
throw uaex;
}
catch
{
return false;
}
}
如果返回结果为真,则调用delete方法。我可以看到所有的文件和子目录都已经被删除了,但是方法抛出了一个异常,“进程无法访问文件'xxxxxxx'”。
如果无法删除整个文件夹,我希望删除操作不会删除文件夹中的任何文件。
【问题讨论】:
-
我看到该函数将返回 true,即使您刚刚实例化了文件的
FileStream。它是一个局部变量,但我不确定垃圾收集器是否会及时释放它以进行下一次操作(删除调用)。您是否尝试过在返回 true 之前手动释放它? -
@Havenard 我想这不是问题,因为
using确保处理流。