如何读取正在使用的文件? [英] How do you read a file which is in use?

查看:24
本文介绍了如何读取正在使用的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.我有一个工具应该每天解析一个日志文件,不幸的是这个日志文件正在被写入日志的进程使用,我无法停止它.

I have a small problem. I have a tool which should parse a log file daily, unfortunately this log file is in use by the process which writes to the log and I cannot stop it.

首先尝试创建文件的副本,这也不起作用.

First try was to create a copy of the file, which is not working either.

有没有办法让我读取日志文件的当前文本,即使它已经在使用中?

Is there any way for me to read the current text of the log file, even if it is already in use?

推荐答案

using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        while (!reader.EndOfStream)
        {

        }
    }
}

FileAccess 指定您想对文件做什么.FileShare 指定 OTHERS 可以在您使用该文件时对其进行哪些操作.

The FileAccess specifies what YOU want to do with the file. The FileShare specifies what OTHERS can do with the file while you have it in use.

在上面的示例中,您可以打开文件进行读取,而其他进程可以打开文件进行读/写访问.在大多数情况下,这适用于打开正在使用的日志文件.

In the example above, you can open a file for reading while other processes can have the file open for read/write access. In most cases, this will work for opening logfiles that are in use.

这篇关于如何读取正在使用的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆