简体   繁体   中英

open file in exclusive mode in C#

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, but not working, even if I opened the foo.txt, I still can reach the Console.WriteLine statement. Any ideas?

static void Main(string[] args)
{
    using (Stream iStream = File.Open("c:\\software\\code.txt", FileMode.Open,
    FileAccess.Read, FileShare.None))
    {
        Console.WriteLine ("I am here");
    }

    return;
}

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

What you have done is correct.

If you need what are all files already opened, then there is a way to see by NtQuerySystemInformation

You may get idea from http://www.codeproject.com/KB/shell/OpenedFileFinder.aspx

which gets all the files opened in a directory.. which can be extended to a single file whether opened or not...

Test it by writing a simple console mode program that opens the file and then waits:

static void Main(string args[])
{
    using (FileStream f = File.Open("c:\\software\\code.txt", FileMode.Open, FileAccess.Read, FileShare.None))
    {
        Console.Write("File is open. Press Enter when done.");
        Console.ReadLine();
    }
}

Run that program from the command line (or another instance of Visual Studio), and then run your program. That way, you can play with different values for FileMode and FileShare to make sure that your program reacts correctly in all cases.

And, no, you don't have to check to see if the file is open first. Your code should throw an exception if the file is already open. So all you have to do is handle that exception.

I would suggest using the FileAccess.ReadWrite member because some files may already be open but allow you Read access on the file. However, I would guess that in non-exceptional conditions, all files open for Read/Write access would not allow your code to Write to the file.

Of course (as Mehrdad already explained), if you are using an editor such as Notepad to open the file as a test, you will not be able to restrict access because Notepad does not lock the file at all.

FileShare.None will only work if another process has also opened the file without allowing it to be shared for reads.

Programs such as Notepad and Visual Studio do not lock text files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM