Search code examples
c#filestreamfile-access

Restrict Access To Certain File From Other Programs And Users While Running


I am in process of building an app which writes data continuously to a file. When I start the program the file is created and starts being written to.
However I noticed that sometimes if I have Windows Explorer open, access to the file is denied to my app, and an error is thrown.

fs = new System.IO.FileStream(location, 
                              System.IO.FileMode.Open, 
                              System.IO.FileAccess.Write, 
                              System.IO.FileShare.ReadWrite);

So how do I restrict access to this file so only my app can access it, not any other programs?


Solution

  • You can change the last parameter from System.IO.FileShare.ReadWrite to System.IO.FileShare.None.

    That locks the file in location exclusively as long as this stream is open and no other app can read, modify or delete that file except your own FileStream.

    In fact this isn't only true for other apps - even your own app can't open another FileStream of that file. So keep it open as long as you need but don't forget to correctly dispose the FileStream after use.