Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c# - Can I prevent a StreamReader from locking a text file whilst it is in use?

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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)) {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...