[英]If streamreader doesn't lock a file just to read it, why is the file locked until a dialogue box is clicked away?
有关StreamReader
大量信息,而不是锁定stackoverflow上的文件,但是对话框是否会以某种方式改变它? 我不得不说不,但是也许我没有正确使用它,并且它正在锁定文件? 我的代码是:
private void read1()
{
TextReader tr = new StreamReader(@"T:\\testfile");
string input = null;
while ((input = tr.ReadLine()) != null)
{
if (input.Contains("test"))
{
MessageBox.Show(input);
}
}
}
我认为您需要使用FileStream来做到这一点。
另外,您不会关闭流或在其上调用Dispose()。 您应该使用using
语句来确保它发生。 以下代码应确保文件未锁定。
private void read1()
{
using (var fs = new FileStream(@"T:\testfile", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using (var tr = new StreamReader(fs)) {
string input = null;
while ((input = tr.ReadLine()) != null)
{
if (input.Contains("test"))
{
MessageBox.Show(input);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.