作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试弄清楚如何使用 FileStream
和 BinaryWriter
编写二进制文件,并在我编写时保持文件锁定以供读取。我特别不希望其他应用程序/进程能够在写入时读取它。
//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/
我是一名优秀的程序员,十分优秀!