How to lock file

前端 未结 2 1759
清歌不尽
清歌不尽 2020-12-06 10:03

please tell me how to lock file in c#

Thanks

相关标签:
2条回答
  • 2020-12-06 10:45

    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.

    0 讨论(0)
  • 2020-12-06 10:58

    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.

    0 讨论(0)
提交回复
热议问题