读取文本文件而不锁定它

时间:2017-06-15 13:34:18

标签: c#

我有一个应用程序(不是由我编写,无法修改代码),它以两种模式运行 - 基于GUI或无声。它将其进度写入日志文件。我编写了一个包装器,将其转换为伪命令行应用程序,使用System.Diagnostics.FileSystemWatcher监视日志文件,并在任何时候更改将最新行写入控制台:

private static void OnChanged(object source, FileSystemEventArgs e)
{
    Console.WriteLine(File.ReadAllLines(e.FullPath).Last());
}

这完全正常,直到日志文件快速连续两次更新,然后app突然发出错误消息:System.IO.IOException: The process cannot access the file '<filepath>\Upgrader.log' because it is being used by another process.

如何在不锁定文件的情况下将日志条目重定向到控制台?我找到this回答,但我不确定如何使用FileStream来获得相同的效果。

编辑:

所以,如果我有一个dict来跟踪日志文件:

Dictionary<string, FileStream> logDict = new Dictionary<string, FileStream>();
Dictionary<string, int> indexDict = new Dictionary<string, int>();

添加一个OnCreated事件处理程序:

private static void OnCreated(object source, FileSystemEventArgs e)
{
    logDict[e.FullPath] = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    indexDict[e.FullPath] = 0;
    OnChanged(source, e);
}

然后将OnChanged更改为

private static void OnChanged(object source, FileSystemEventArgs e)
{
    using (StreamReader sr = new StreamReader(logDict[e.FullPath]))
    {
        for (int i = 0; i < indexDict[e.FullPath]; i++)
            sr.ReadLine();
        Console.WriteLine(sr.ReadLine());
        indexDict[FullPath]++;
        sr.Close();
    }
}

应该有用吗?

再次编辑:我想我有一个解决方案。试过这个似乎有效:

Dictionary<string, int> indexDict = new Dictionary<string, int>();

private static void OnChanged(object source, FileSystemEventArgs e)
{
    if (!indexDict.Keys.Contains(e.FullPath))
        indexDict[e.FullPath] = 0;
    using (FileStream fs = new FileStream(e.Full Path,
                                          FileMode.Open,
                                          FileAccess.Read,
                                          FileShare.ReadWrite))
    {
        using (StreamReader sr = new StreamReader(fs))
        {
            for (int i = 0; i < indexDict[e.FullPath]; i++)
                sr.ReadLine();
            Console.WriteLine(sr.ReadLine());
            indexDict[e.FullPath]++;
            sr.Close();
        }
    }
}

0 个答案:

没有答案