在 C# 和 Windows 中写入事务性文件? [英] Transactional file writing in C# and Windows?

查看:24
本文介绍了在 C# 和 Windows 中写入事务性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据文件,有时我需要对文件进行更改.更改包括在多个地方更改信息.例如,更改文件末尾附近的一些数据以及更改开头附近的一些信息.我希望两个单独的写入要么都成功,要么都失败,否则它会处于不确定状态并被有效破坏.在 .NET 或一般情况下,是否有针对此方案的任何内置支持?

I have a data file and from time to time I need to write a change to the file. The change consists of changing information in more than one place. For example, changing some data near the end of the file and also changing some information near the start. I want the two separate writes to either both succeed or both fail, otherwise it is left in uncertain state and effectively corrupted. Is there any builtin support for this scenario in .NET or in general?

如果不是那么其他人如何解决这个问题?Windows 上的数据库如何解决这个问题?

If not then how to others solve this issue? How does a database on Windows solve this issue?

更新:我不想使用事务性 NTFS 功能,因为它在旧版本的 Windows(如 XP)上不可用,并且在上述文件覆盖场景中速度很慢.>

UPDATE: I do not want to use the Transactional NTFS capability because it is not available on older version of Windows such as XP and it is slow in the file overwrite scenario as described above.

推荐答案

如果您使用的是 Windows 6 或更高版本 (Vista/7/2008/2008R2),NTFS 文件系统支持事务(包括在分布式事务中):但您将需要使用 P/Invoke 来调用 Win32 API(请参阅此问题).

If you are using Windows 6 or later (Vista/7/2008/2008R2) the NTFS filesystem supports transactions (including within a distributed transaction): but you will need to use P/Invoke to call Win32 APIs (see this question).

如果您需要在旧版本的 Windows 或非 NTFS 分区上运行,则需要自己执行事务.这绝对是不平凡的:在跨进程和系统处理多个进程(包括通过共享的远程访问)时获得完整的 ACID 功能即使假设只会使用您的访问方法(使用普通 Win32 API 的其他一些进程当然会打破东西).

If you need to run on older versions of Windows, or non-NTFS partitions you would need to perform the transactions yourself. This is decidedly non-trivial: getting full ACID functionality while handling multiple processes (including remote access via shares) across process and system crashes even with the assumption that only your access methods will be used (some other process using normal Win32 APIs would of course break things).

在这种情况下,数据库几乎肯定会更容易:有许多进程内数据库(SQL Compact Edition、SQL Lite 等),因此数据库不需要服务器进程.

In this case a database will almost certainly be easier: there are a number of in-process databases (SQL Compact Edition, SQL Lite, ...) so a database doesn't require a server process.

这篇关于在 C# 和 Windows 中写入事务性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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