且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#文件移动并覆盖

更新时间:2023-02-20 18:06:50

除非在文件系统中通过 Delete 调用触发了某些事件(这不是实际上已删除,直到通话返回后不久.几个选项:

Not sure why this would happen unless there's some event triggered in the file system by the Delete call which means it's not actually deleted until slightly after the call returns. A few options:

  • 您可以进行循环操作(在出错之前具有某种程度的最大循环次数),以便在尝试移动之前先检查文件是否存在,如果删除后文件仍然存在,可以短暂进入睡眠状态
  • 您可以使用 File.Copy(sidetapedata,sidetapedata2,true)复制而不是移动,然后删除源文件.但是,如果移动将通过简单的文件系统目录条目更改(而不是真正地复制数据)来处理,则效率会降低
  • 您可以在目标文件上使用 File.Move 而不是 File.Delete 将其移动到其他无害的文件名,然后将其删除,希望 Move Delete 更具原子性.
  • You could loop (with some sort of maximum number of loops before erroring) where you check for the file's existence before trying the move, and sleep briefly if it still exists after deletion
  • You could use File.Copy(sidetapedata, sidetapedata2, true) to copy instead of moving, and then delete the source file. This will be less efficient though, assuming the move would be handled by a simple file system directory entry change (rather than really copying the data)
  • You could use File.Move on the target file instead of File.Delete to move it to some harmless other filename, then delete that afterwards, hoping that the Move is more atomic than the Delete.

怀疑这里的线程无关紧要-我建议您编写一个简短但完整的程序来验证这一点,以便您可以排除它(并轻松测试变通方法).

I suspect the threading is irrelevant here - I suggest you write a short but complete program to validate that, so you can rule it out (and easily test the workarounds).