How to lock file

2019-01-15 06:15发布

问题:

please tell me how to lock file in c#

Thanks

回答1:

Simply open it exclusively:

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

Ref.

Update: In response to comment from poster: According to the online MSDN doco, File.Open is supported in .Net Compact Framework 1.0 and 2.0.



回答2:

FileShare.None would throw a "System.IO.IOException" error if another thread is trying to access the file.

You could use some function using try/catch to wait for the file to be released. Example here.

Or you could use a 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" statement in the actual writing function itself (i.e. inside AddLog) instead of in the background worker's functions.