Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I lock a file while writing to it via a FileStream?

Tags:

c#

io

I am trying to figure out how to write a binary file with a FileStream and BinaryWriter, and keep the file locked for read while I am writing. I specifically don't want other applications/processes to be able to read from the while while its being written to.

//code to declare ba as a byte array

//dpath is the path to the file

FileStream BinaryFile = new FileStream(dpath, FileMode.Create, FileAccess.Write);

BinaryWriter Writer = new BinaryWriter(BinaryFile);

Writer.Write(ba);

Writer.Close();

BinaryFile.Dispose();

Now the problem is the file can be opened by other applications during the write, which is undesirable in my current application. The FileStream has a Lock Method, but that locks for writing and not for reading, so that doesn't help me.

like image 291
Steed Avatar asked Nov 10 '09 11:11

Steed


1 Answers

You're looking for the fourth parameter of the FileStream Constructor.

public FileStream(
    string path,
    FileMode mode,
    FileAccess access,
    FileShare share
)

So in your case:

FileStream BinaryFile = new FileStream(dpath, FileMode.Create,
                                       FileAccess.Write, FileShare.None);

FileShare-Enum:

Contains constants for controlling the kind of access other FileStream objects can have to the same file.

Members:

  • None, Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
  • Read, Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
  • Write, Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
  • ReadWrite, Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
  • Delete, Allows subsequent deleting of a file.
  • Inheritable, Makes the file handle inheritable by child processes. This is not directly supported by Win32.
like image 169
Bobby Avatar answered Sep 26 '22 01:09

Bobby