open file in exclusive mode in C#

后端 未结 5 1090
时光说笑
时光说笑 2020-11-30 08:40

I want to open a file for read in exclusive mode, and if the file is already opened by some process/thread else, I want to receive an exception. I tried the following code,

5条回答
  •  情书的邮戳
    2020-11-30 09:26

    What you are doing is the right thing. Probably you are just testing it incorrectly. You should open it with a program that locks the file when it's open. Notepad wouldn't do. You can run your application twice to see:

    static void Main(string[] args)
    {
        // Make sure test.txt exists before running. Run this app twice to see.
        File.Open("test.txt", FileMode.Open, FileAccess.Read, FileShare.None);
        Console.ReadKey();
    }
    

提交回复
热议问题