在.NET中,是否可以以非独占写访问方式打开文件?如果可以,如何操作?我希望有两个或更多进程可以同时写入同一个文件。
编辑:这是问题的背景:我正在为IIS编写一个简单的日志记录HTTPModule。由于在不同应用程序池中运行的应用程序作为不同的进程运行,因此我需要一种在进程之间共享日志文件的方法。我可以编写复杂的文件锁定例程或惰性写入器,但这是一个丢弃的项目,所以这并不重要。
这是我用来测试该过程的代码。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace FileOpenTest
{
class Program
{
private static bool keepGoing = true;
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
Console.Write("Enter name: ");
string name = Console.ReadLine();
//Open the file in a shared write mode
FileStream fs = new FileStream("file.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
while (keepGoing)
{
AlmostGuaranteedAppend(name, fs);
Console.WriteLine(name);
Thread.Sleep(1000);
}
fs.Close();
fs.Dispose();
}
private static void AlmostGuaranteedAppend(string stringToWrite, FileStream fs)
{
StreamWriter sw = new StreamWriter(fs);
//Force the file pointer to re-seek the end of the file.
//THIS IS THE KEY TO KEEPING MULTIPLE PROCESSES FROM STOMPING
//EACH OTHER WHEN WRITING TO A SHARED FILE.
fs.Position = fs.Length;
//Note: there is a possible race condition between the above
//and below lines of code. If a context switch happens right
//here and the next process writes to the end of the common
//file, then fs.Position will no longer point to the end of
//the file and the next write will overwrite existing data.
//For writing periodic logs where the chance of collision is
//small, this should work.
sw.WriteLine(stringToWrite);
sw.Flush();
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
keepGoing = false;
}
}
}