C#文件移动并覆盖 [英] c# file move and overwrite

查看:221
本文介绍了C#文件移动并覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个多线程应用程序.我的代码中有某处:

I'm developing a multi threaded application. I have somewhere in my code :

File.Delete(sidetapedata);
File.Move(sidetapedata2, sidetapedata); //sidetapedata and sidetapedata2 are two file paths that correspond to sidetapedata.txt and sidetaptdata2.txt in some directory.

第二行有时可以正常运行,有时会抛出 IOException :

The second line sometimes runs fine and other times, it throws an IOException :

Cannot create a file when that file already exists.

还有一个线程正在访问 sidetapedata 文件,但是一个线程仅在读取该文件,而没有写操作.我 am 使用锁来保护比赛条件.不知道为什么会这样.

There is one more thread that is accessing the sidetapedata file but that one is only reading this file, no write operations. I am using locks to protect race conditions. Don't know why this is happening.

更新 :即使可视c#调试器向我显示此异常,但查看包含这些文件的目录时,我也看不到 sidetapedata.txt 文件,但是有一个 sidetapedata2.txt 文件!

UPDATE : even when visual c# debugger shows me this exception, looking into the directory that contains these files, I see there is no sidetapedata.txt file but there is a sidetapedata2.txt file!

UPDATE2 :同样,仅当 sidetapedata.txt sidetapedata2.txt 都为空白时,才会发生此行为

UPDATE2 : Also, this behavior only happens when sidetapedata.txt and sidetapedata2.txt are both blank

推荐答案

除非在文件系统中通过 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).

这篇关于C#文件移动并覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆