问题描述
该StreamReader的锁定,而它的文本文件阅读。
我可以强制的StreamReader在只读或非锁定模式下工作?
我的解决方法是将文件复制到一个临时位置,并从那里读取它,但我会preFER如果可能的话直接使用的StreamReader。任何替代suggetions?
背景:
我写了一个小的应用程序得到一些统计出来的日志文件中。该文件不断被由外部程序更新(几次),让通话AAXXYY。
回顾输出表明我的应用程序可以从写锁定的文件和preventing AAXXYY。
这是我在做什么。
私人无效btnGetStats_Click(对象发件人,EventArgs的)
{
INT countStarts = 0;
INT countEnds = 0;
IList的<字符串>会议=新的名单,其中,串>();
使用(StreamReader的stRead =新的StreamReader(openFileDialog1.FileName,Encoding.Uni code))
{
而(!stRead.EndOfStream)
{
串线= stRead.ReadLine();
如果(line.Contains(会话启动))
{
countStarts ++;
sessions.Add(line.Substring(line.IndexOf([),line.LastIndexOf(]) - line.IndexOf([)));
}
如果(line.Contains(会议结束))
{
countEnds ++;
sessions.Remove(line.Substring(line.IndexOf([),line.LastIndexOf(]) - line.IndexOf([)));
}
}
}
txtStarts.Text = countStarts.ToString();
txtEnds.Text = countEnds.ToString();
txtDifference.Text =(countStarts - countEnds)的ToString();
listBox1.DataSource =会议;
}
您可以通过一个FileStream的StreamReader的,并创建正确的文件共享价值的FileStream。例如:
使用(var文件=新的FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
使用(VAR读卡器=新的StreamReader(文件,Encoding.Uni code)){
}
The StreamReader locks a text file whilst it is reading it.
Can I force the StreamReader to work in a "read-only" or "non locking" mode?
My workaround would be to copy the file to a temp location and read it from there but I would prefer to use the StreamReader directly if possible.Any alternative suggetions?
Background:
I've written a small app to get some stats out of a log file. This file is constantly being updating (several times a second) by an outside program lets call AAXXYY.
Reviewing the output suggests that my app may be locking the file and preventing AAXXYY from writing.
This is what I'm doing
private void btnGetStats_Click(object sender, EventArgs e)
{
int countStarts = 0;
int countEnds = 0;
IList<string> sessions = new List<string>();
using(StreamReader stRead = new StreamReader(openFileDialog1.FileName,Encoding.Unicode))
{
while(!stRead.EndOfStream)
{
string line = stRead.ReadLine();
if(line.Contains("Session start"))
{
countStarts++;
sessions.Add(line.Substring(line.IndexOf("["), line.LastIndexOf("]") - line.IndexOf("[")));
}
if (line.Contains("Session end"))
{
countEnds++;
sessions.Remove(line.Substring(line.IndexOf("["), line.LastIndexOf("]") - line.IndexOf("[")));
}
}
}
txtStarts.Text = countStarts.ToString();
txtEnds.Text = countEnds.ToString();
txtDifference.Text = (countStarts - countEnds).ToString();
listBox1.DataSource = sessions;
}
You can pass a FileStream to the StreamReader, and create the FileStream with the proper FileShare value. For instance:
using (var file = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader (file, Encoding.Unicode)) {
}
这篇关于我可以prevent从锁定一个文本文件,而这是在使用一个StreamReader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!