如何在 C# 中进行原子写入/追加,或者如何使用 FILE_APPEND_DATA 标志打开文件? [英] How can I do an atomic write/append in C#, or how do I get files opened with the FILE_APPEND_DATA flag?
问题描述
在大多数符合 Unix 和 Posix 的操作系统下,使用 O_APPEND 执行 open() 操作系统调用向操作系统表明写入是原子追加和写入操作.通过这种行为,对于本地文件系统,当您进行写入时,您知道它会附加到文件末尾.
Under most Unixes and Posix conforming operating systems performing an open() operating system call with the O_APPEND indicates to the OS that writes are to be atomic append and write operations. With this behavior,for local filesystems when you do a write, you know it get appended to the end of the file.
Windows 操作系统通过将 FILE_APPEND_DATA
中的适当参数传递给 Win32 CreateFile() 系统调用来支持相同的功能.
The Windows operating systems support the same functionality by passing FILE_APPEND_DATA
in the appropriate parameter to the Win32 CreateFile() system call.
参考:
http://www.google.com/search?q=msdn+createfile
or: http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx
http://www.google.com/search?q=msdn+IoCreateFileSpecifyDeviceObjectHint
or: http://www.google.com/search?q=msdn+IoCreateFileSpecifyDeviceObjectHint
我的问题是,我无法确定如何使用 Net Framework 在 C# 下获得此行为图书馆,有没有办法使用 Net Framework 获得这种行为?顺便说一下,我不相信使用 FileMode.Append 会产生这种行为.
My problem is this, I cannot determine how to get this behavior under C# using the Net Framework Libraries, is there a way to get such behavior using the Net Framework? I do not believe using FileMode.Append gives such behavior, by the way.
推荐答案
使用 FileStream
构造函数的重载之一:
Use one of the overloads of the FileStream
constructor:
new FileStream(FileName, FileMode.Open, FileSystemRights.AppendData,
FileShare.Write, 4096, FileOptions.None)
FileSystemRights.AppendData
对应于 FILE_APPEND_DATA
FileStream 似乎坚持缓冲,因此请确保缓冲区对于每个每次写入后写入并调用 Flush()
.
FileStream seems to insist on buffering, so make sure the buffer is large enough for each
write and call Flush()
after each write.
小例子:
private void button1_Click(object sender, EventArgs e) {
Thread t1 = new Thread(DoIt);
Thread t2 = new Thread(DoIt);
t1.Start("a");
t2.Start("b");
Thread.Sleep(2000);
Environment.Exit(0);
}
private void DoIt(object p) {
using (FileStream fs = new FileStream(FileName, FileMode.Open, FileSystemRights.AppendData,
FileShare.Write, 4096, FileOptions.None)) {
using (StreamWriter writer = new StreamWriter(fs)) {
writer.AutoFlush = true;
for (int i = 0; i < 20; ++i)
writer.WriteLine("{0}: {1:D3} {2:o} hello", p, i, DateTime.Now);
}
}
}
这篇关于如何在 C# 中进行原子写入/追加,或者如何使用 FILE_APPEND_DATA 标志打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!