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,
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.