【发布时间】:2011-04-18 15:11:05
【问题描述】:
我们有一个 MoveFile 方法,该方法通常可以工作,但在客户站点总是失败。
if (File.Exists(target))
{
File.Delete(target);
}
File.Move(source, target);
对File.Move 的调用反复失败
System.IO.IOException: Cannot create a file when that file already exists. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.__Error.WinIOError() at System.IO.File.Move(String sourceFileName, String destFileName)
我们对该方法的调用进行了错误处理,但我们无法弄清楚为什么File.Delete 不起作用并且没有抛出任何东西。
我们虽然是关于文件权限的,但是File.Delete 会抛出一个UnauthorizedAccessException。
当File.Move 在删除该特定文件之前,是否有任何其他原因会导致“文件已存在”失败?
【问题讨论】:
-
好奇:如果将 File.Move 包装在类似的 if(File.Exists(..)) 中会发生什么?
-
删除后移动失败的一个可能原因是文件句柄可能仍在系统的某些进程中打开,例如防病毒扫描程序或搜索索引器。由于 File.Delete 备注部分明确指出“Windows NT 4.0 平台注意:Delete 不会删除为正常 I/O 打开的文件或内存映射的文件。”,而是将其标记为 Delete 并进一步调用访问被拒绝异常。