问题描述
来自File.Move
的文档:
请注意,如果您尝试通过将同名文件移动到该目录来替换文件,则会收到 IOException.您不能使用 Move 方法覆盖现有文件.
Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. You cannot use the Move method to overwrite an existing file.
简而言之,您不能在 Move
上进行覆盖,因此为了便于在 Move 上覆盖,我通过执行 File.Copy
后跟 <代码>文件.删除代码>.比如:
In short, you can't overwrite on Move
, so in order to facilitate overwriting on Move I mimic the behavior by doing a File.Copy
followed by a File.Delete
. Something like:
if (File.Exists(dstFileName))
{
// System.IO.File.Move cannot be used to overwrite existing files, so we're going
// to simulate that behavior with a Copy & Delete.
File.Copy(procContext.FileName, dstFileName);
File.Delete(procContext.FileName);
}
else
File.Move(procContext.FileName, dstFileName);
我的问题是:我需要注意哪些可能导致源文件在未成功复制的情况下被删除的情况?
My question is: Are there any situations that I need to guard against which could lead to the source file being deleted without it first being successfully copied?
我通过阅读文档的理解是,由于 File.Copy
不返回任何内容,因此它应该在任何情况下都不会成功抛出异常.有没有人遇到过不正确的情况?
My understanding from reading the documentation is that since File.Copy
doesn't return anything that it should throw an exception in any case that it doesn't succeed. Has anyone encountered any situations where this isn't true?
推荐答案
建议你先探测一下目标文件是否存在,如果存在就删除.然后执行正常的移动操作.
I suggest you to probe first if the target file exists and if yes, delete it. Then execute a normal move operation.
由于这个序列不是原子的,如果目标存在,您可能希望重命名它而不是删除它,以避免在移动失败时丢失它.
Since this sequence is not atomic, in case the destination exists you might want to rename it instead of deleting it, to avoid losing it in case the move fails.
这篇关于如果目标已存在,则模拟 File.Move的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!