gpt4 book ai didi

c# - 如何在通过 FileStream 写入文件时锁定文件?

转载 作者:可可西里 更新时间:2023-11-01 08:57:21 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何使用 FileStreamBinaryWriter 编写二进制文件,并在我编写时保持文件锁定以供读取。我特别不希望其他应用程序/进程能够在写入时读取它。

//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();

现在的问题是文件可以在写入期间被其他应用程序打开,这在我当前的应用程序中是不希望的。 FileStream 有一个 Lock 方法,但它锁定写入而不是读取,所以这对我没有帮助。

最佳答案

您正在寻找 fourth parameter of the FileStream Constructor .

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

所以在你的情况下:

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

FileShare -枚举:

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.

关于c# - 如何在通过 FileStream 写入文件时锁定文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1707196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com