views:

420

answers:

2

Hi,

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 dont 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 app. The FileStream has a Lock Method, but that locks for writing and not for reading, so that doesnt help me. Searching google and similar finds way more info for object locks with threading than for file locks.

Can anyone guide me ?

Thanks,

Steed.

+14  A: 

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

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

I don't know if it is possible.

For instance Firefox stores files while downloading using another name until they are finished. When everything is there, it renames it to the original name. A different file suffix will avoid that users try to open it with a double click.

Stefan Steinegger