Dot-Net
如何使用 .NET 打開文件以進行非獨占寫入訪問
是否可以在 .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; } } }
使用File.Open 打開文件時使用FileShare列舉。具體來說,使用 FileShare.ReadWrite。
FileStream 類有一個建構子,它接受多個選項,包括FileShare
new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);