open file in exclusive mode in C#
Solution 1:
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();
}
Solution 2:
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.