Recently I was working on some code where it was required to open a file, write something to it and close it. I ran into a small problem while considering the code. Since this was a Doc file the problem was that how do I check if the file was already open or not? If the file is already open for editing by some other user, how do I write to it?
Like all good programmers I looked around for a code sample on the Internet, although I found some great examples on the net, I didn't find a good C# sample available for re-use. So I thought I will just post what I wrote. So here is the complete code listing...
public static string __message;
static void Main(string args)
string _path = "D:\\projects\\test.doc";
retVal = FileInUse(_path);
Console.WriteLine("File is available for editing");
static bool FileInUse(string path)
//Just opening the file as open/create
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
//If required we can check for read/write by using fs.CanRead or fs.CanWrite
catch (IOException ex)
//check if message is for a File IO
__message = ex.Message.ToString();
if (__message.Contains("The process cannot access the file"))
Actually, I don't really like this code a lot. One of the things I was considering was to do was to use the System.Runtime.InteropServices.Marshal.GetHRForException then get the HRESULT and convert this to a Win32 exception and then see if there is a SHARING VIOLATION. But there is no easy way to convert a HRESULT to a Win32 exception. Also, like the above example its again dependent on the implementation details by Microsoft. In this example, I am just parsing the exception message to see if there is a reference to a file in use, which might of course always change later.
One another thing I am doing in the code above is "throwing" the exception and not catching any default exceptions. A lot of programmers will probably look at me with raised eyebrows but somehow after spending almost 3 years in support, I really like to see a nice stack trace from which I can infer where the problem is coming from. Again its just an implementation detail, you can always change and write the error to an event log or log file.