开发者

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

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

//dpa开发者_如何学编程th 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜