问题描述
在大多数的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框架下得到C#这种行为
图书馆,有没有办法使用.NET框架来获得这样的行为?
我不相信使用FileMode.Append给出了这样的行为,顺便说一句。
My problem is this, I cannot determine how to get this behavior under C# using the Net FrameworkLibraries, 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 code>与
FILE_APPEND_DATA对应
的FileStream似乎坚持缓冲,所以一定要确保缓冲区足够大的每个
写和呼叫同花顺()
每次写操作之后。
FileStream seems to insist on buffering, so make sure the buffer is large enough for eachwrite 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标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!