0

该程序的一个功能基本上需要跟踪一个日志文件并转发新写入的行。我相信我通过FileStreamFileShare.ReadWrite选项创建为流来正确执行此操作,如此此处StreamReader的其他几个答案中所述。

但是当我运行程序时,它会阻止某些进程写入文件。使用进程监视器,我可以看到我的程序正在打开具有 R/W 权限的文件,而不仅仅是读取。

reader = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

{
    //start at the end of the file
    long lastMaxOffset = reader.BaseStream.Length;

    while (true)
    {
        System.Threading.Thread.Sleep(Properties.Settings.Default.pauseInMilliseconds);

        // if the file size has not changed, keep idling
        if (reader.BaseStream.Length == lastMaxOffset)
            continue;

        // handle if the file contents have been cleared
        if (reader.BaseStream.Length < lastMaxOffset)
            lastMaxOffset = 0;
        eventLogger.WriteEntry("LogChipper target file was reset, starting from beginning", EventLogEntryType.Information, 0);

        // seek to the last max offset
        reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

        // read out of the file until the EOF
        string line = "";
        while ((line = reader.ReadLine()) != null)
            syslogForwarder.Send(line);

        // update the last max offset
        lastMaxOffset = reader.BaseStream.Position;

        // block if the service is paused or is shutting down
        pause.WaitOne();
    }
}

我在保持文件打开的那个块中还有其他事情吗?FileSystemWatcher如果那会更好,我愿意尝试不同的方法(例如)...

4

0 回答 0