How to lock a file

tell me how to lock a file in C #

thank

+16
c # windows-mobile compact-framework
Sep 16 '09 at 9:53
source share
4 answers

Just open it:

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

Link

Refresh . In response to the comment from the poster. According to the online protocol

+41
Sep 16 '09 at 9:59
source share
β€” -

This is equivalent to Mitch's answer, except that it is available in other versions of .Net. The only significant argument is FileShare.None ; others allow you to overload the constructor, but their values ​​are determined by how you use the stream.

 using(var fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None) { // ... } 
0
Jan 11 '16 at 21:49
source share

FileShare.None will throw a "System.IO.IOException" error if another thread tries to access the file.

You can use some function using try / catch to wait for the file to exit. An example is here .

Or you can use the lock statement with some dummy variable before accessing the write function:

  // The Dummy Lock public static List<int> DummyLock = new List<int>(); 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); } } } 

You can also use the "lock" operator in the actual write function (i.e. inside AddLog), and not in the background working functions.

0
May 28 '17 at 9:07 a.m.
source share

You tried to do this, https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream.lock?view=netframework-4.8 explains how to lock a file using a file stream in C #

0
Jun 14 '19 at 5:17
source share



All Articles