![](/img/trans.png)
[英]C# Read text file that is fully locked or read output outside if statement
[英]C# read locked file
到目前为止,我已经尝试了所有方法,但均未成功。
我想要完成的是,我想打开并锁定文件一段时间。 打开并锁定文件后,我立即尝试打开同一文件以供读取。
string filePath = "test.ini";
// Open and lock the file
FileStream configurationFile = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
configurationFile.Lock(1, configurationFile.Length);
// Open the same file just to read it
using (FileStream bufferStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(bufferStream))
{
string line;
while ((line = sr.ReadLine()) != null) // <--- Here I get the error
{
CustomMessageBox.Show(line);
}
}
}
我实际上可以使用FileStream和StreamReader打开文件,但是当要使用StreamReader与sr.ReadLine()之类的文件时,它将引发异常,表明该文件正在由另一个进程使用。
正如这里提到的, 读取另一个进程使用的文件[重复] FileShare属性应该为ReadWrite,但这没有帮助。
我也尝试了所有可用的编码,例如StreamReader(bufferStream, Encoding.*)
但是那也不起作用。
有什么简单的我可以忽略的吗?
这是因为根据Windows,您正在为文件构建新的句柄。 当文件被锁定时,它不允许任何其他句柄被其他流获取。 您最好像这样修复代码:
using (FileStream bufferStream = new FileStream(filePath, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
{
bufferStream.Lock(0L, bufferStream.Length);
using (StreamReader sr = new StreamReader(bufferStream))
{
string line;
while ((line = sr.ReadLine()) != null) // <--- Here I get the error
{
CustomMessageBox.Show(line);
}
}
// dispose lock
bufferStream.Unlock(0L, bufferStream.Length);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.