如何锁定文件

时间:2009-09-16 09:53:33

标签: c# .net windows-mobile compact-framework

请告诉我如何在c#

中锁定文件

由于

2 个答案:

答案 0 :(得分:41)

只需打开它:

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

Ref

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

答案 1 :(得分:0)

FileShare.None会抛出一个" System.IO.IOException"如果另一个线程正在尝试访问该文件,则会出错。

您可以使用try / catch等一些函数来等待文件被释放。示例here

或者你可以使用一些" dummy"访问write函数之前的变量:

    // 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);
            }
        }

    } 

您还可以使用&#34;锁定&#34;实际写入函数本身(即在AddLog内部)而不是在后台工作程序函数中的语句。