Ist es möglich, eine Datei in .NET mit nicht exklusiven Schreibzugriff zu öffnen? Wenn das so ist, wie? Ich hoffe, dass zwei oder mehr Prozesse gleichzeitig in dieselbe Datei schreiben.So öffnen Sie eine Datei für nicht-exklusiven Schreibzugriff mit .NET
Bearbeiten: Hier ist der Kontext dieser Frage: Ich schreibe eine einfache Protokollierung HTTPModule für IIS. Da Anwendungen, die in verschiedenen App-Pools ausgeführt werden, als separate Prozesse ausgeführt werden, muss die Protokolldatei zwischen Prozessen geteilt werden. Ich könnte eine komplexe Dateisperrroutine oder einen faulen Autor schreiben, aber das ist ein Wegwerfprojekt, also ist es nicht wichtig.
Dies ist der Testcode ich den Prozess, herauszufinden, verwendet.
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;
}
}
}
Ich nehme an, Sie bedeuten, dass andere sie lesen können, während Sie schreiben - es scheint seltsam mehrere Autoren ermöglichen zu wollen. –