C# 以事务方式交换两个文件夹
我有两个文件夹,例如“C:\Working”和“C:\Final”。我有一个缓慢的程序,可以在需要时处理“C:\Working”中收到的数据。
当操作“C:\Working”内数据的过程完成后,我想用最新信息替换旧数据(“C:\Final”内)到“C:\Working”(信息到“C:\工作”始终是完整且最新的)。
所以基本上我想:
- 在“C:_Final”中重命名
- “C:\Final”在“C:\Final”中重命名“C:\Working”
- 删除“C:_Final”
- 创建“C:\Working”(现在为空) )
这样,应用程序(使用“C:\Final”)必须等待的时间就很短。
因此,我想到的唯一想法是:
Directory.Move("C:\Final\","C:\_Final\");
Directory.Move("C:\Working\","C:\Final\");
Directory.Delete("C:\_Final\",true);
Directory.CreateDirectory("C:\Working\");
但我认为有更好的方法,在我看来,这种方法有点棘手,如果出现问题(移动、删除或创建),文件夹结构将保持不一致。 所以我想问是否有更好的方法,我希望有一种原子交换目录的方法。
I have two folder, for example "C:\Working" and "C:\Final". I have a slow procedure that will crunch data received in "C:\Working" when needed.
When the procedure that manipulate data inside "C:\Working" has finished i would like replace the old data (inside "C:\Final") with the latest information into "C:\Working" (the information into "C:\Working" are always complete and up to date).
So basically i would like to :
- rename "C:\Final" in "C:_Final"
- rename "C:\Working" in "C:\Final"
- delete "C:_Final"
- create "C:\Working" (now empty)
In that way the time in which the application (that use "C:\Final") have to wait is small.
So the only idea that come to mind was the subsequent :
Directory.Move("C:\Final\","C:\_Final\");
Directory.Move("C:\Working\","C:\Final\");
Directory.Delete("C:\_Final\",true);
Directory.CreateDirectory("C:\Working\");
But i image there are a better approach, this method is a bit triky in my opinion and if there is an issue (moving, deleting or creating) the folder structure remain inconsistent.
So i would ask if there is a better aproach, i hope for a way to atomically swap directory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过对 NTFS 原子操作和此类操作的 NET Framework 支持的一些研究后,我发现建议在处理文件系统操作时使用事务来实现原子性的主题。
似乎还表明,即使文件系统操作本身不支持事务;有一个 Nuget 包(TxFileManager)专注于为文件系统操作提供事务支持。
因此,事务和上面提到的包的组合应该允许对文件系统进行原子操作
After a bit of research about NTFS atomic operation and support of NET Framework of such kind of operation, i found out topic that sugget using transaction to implement atomicity among when you deal with file system operation.
Seems also that, even if natively the file system operations do not support transaction; there is a Nuget package (TxFileManager) that is focused on provide transactional support over file system operations.
So a combination of transaction and the package mentioned above should allow atomic operation over file system