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

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

问题描述

我有一个小问题。我有一个工具,它应该每天分析日志文件,可惜这日志文件正在使用由写入日志的过程中,我不能阻止它。

首先尝试是创建文件,它也不工作的副本。

有没有办法对我来说,读取日志文件的当前文本,即使它已在使用?


解决方案
使用

 (的FileStream流= File.Open(文件路径,FileMode.Open,FileAccess.Read,文件共享.ReadWrite))
{
    使用(StreamReader的读者=新的StreamReader(流))
    {
        而(!reader.EndOfStream)
        {        }
    }
}

该FileAccess的指定你想用文件做。
文件共享指定其他人可以对文件,而你在使用中有它做的。

在上面的例子中,你可以打开一个文件进行读取,而其他进程可以打开的读/写访问的文件。在大多数情况下,这将用于打开使用中的日志文件工作。

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

        }
    }
}

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天全站免登陆