我可以阻止 StreamReader 在使用文本文件时锁定该文件吗?

发布于 2024-08-09 09:01:39 字数 1412 浏览 1 评论 0原文

StreamReader 在读取文本文件时锁定该文件。
我可以强制 StreamReader 在“只读”或“非锁定”模式下工作吗?

我的解决方法是将文件复制到临时位置并从那里读取它,但如果可能的话,我更愿意直接使用 StreamReader。 还有其他建议吗?

背景:
我编写了一个小应用程序来从日志文件中获取一些统计信息。该文件由外部程序不断更新(每秒几次),我们调用 AAXXYY。

查看输出表明我的应用程序可能正在锁定文件并阻止 AAXXYY 写入。

这就是我正在做的

    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;
    }

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;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨落□心尘 2024-08-16 09:01:39

您可以将 FileStream 传递给 StreamReader,并使用正确的 FileShare 值创建 FileStream。例如:

using (var file = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader (file, Encoding.Unicode)) {
}

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)) {
}
爱冒险 2024-08-16 09:01:39

我想添加一些上下文,StreamReader 在读取文件时不会锁定文件以供读取仅用于写入。看一下 StreamReader 类中的以下代码。

 new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan);

请注意 MSDN http://msdn 采用的默认 FileAccess.Read 参数.microsoft.com/en-us/library/system.io.fileshare.aspx

允许随后打开文件进行读取。如果未指定此标志,则任何打开文件进行读取的请求(通过此进程或另一个进程)都将失败,直到文件关闭为止。但是,即使指定了此标志,可能仍然需要额外的权限才能访问该文件。

再次取自 MSDN,以允许读取和写入使用 FileAccess.ReadWrite 代替(如 Jb Evain 所建议)。

允许随后打开文件进行读取或写入。如果这个
未指定标志,任何打开文件进行读取的请求或
写入(通过此进程或另一个进程)将失败,直到文件
已关闭。然而,即使指定了该标志,附加的
可能仍需要权限才能访问该文件。

Thought I'd add some context, StreamReader does not lock a file for reading only for writing whist it is being read. Take a look at the code below from the StreamReader class.

 new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan);

Notice the default FileAccess.Read parameter taken for MSDN http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

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.

Again taken from MSDN to allow reading and writing use FileAccess.ReadWrite instead (as suggested by Jb Evain).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文