如何锁定文件

请告诉我如何在c#中锁定文件

谢谢

只需打开它:

using (FileStream fs = File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None)) { // use fs } 

参考

更新 :回应海报的评论:根据在线MSDN doco ,.Net Compact Framework 1.0和2.0支持File.Open。

如果另一个线程正在尝试访问该文件,FileShare.None将抛出“System.IO.IOException”错误。

你可以使用一些函数使用try / catch来等待文件被释放。 这里的例子。

或者你可以在访问write函数之前使用带有一些“dummy”变量的lock语句:

  // The Dummy Lock public static List DummyLock = new List(); static void Main(string[] args) { MultipleFileWriting(); Console.ReadLine(); } // Create two threads private static void MultipleFileWriting() { BackgroundWorker thread1 = new BackgroundWorker(); BackgroundWorker thread2 = new BackgroundWorker(); thread1.DoWork += Thread1_DoWork; thread2.DoWork += Thread2_DoWork; thread1.RunWorkerAsync(); thread2.RunWorkerAsync(); } // Thread 1 writes to file (and also to console) private static void Thread1_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i < 20; i++) { lock (DummyLock) { Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - 3"); AddLog(1); } } } // Thread 2 writes to file (and also to console) private static void Thread2_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i < 20; i++) { lock (DummyLock) { Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - 4"); AddLog(2); } } } private static void AddLog(int num) { string logFile = Path.Combine(Environment.CurrentDirectory, "Log.txt"); string timestamp = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"); using (FileStream fs = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.None)) { using (StreamWriter sr = new StreamWriter(fs)) { sr.WriteLine(timestamp + ": " + num); } } } 

您还可以在实际的写入函数本身(即AddLog内部)中使用“lock”语句,而不是在后台worker的函数中。