为什么这会锁定文件?

时间:2013-02-18 19:59:04

标签: c# file-io .net-3.5

该程序的一个特性基本上需要拖尾日志文件并转发新写入的行。我相信我是通过使用FileStream选项创建FileShare.ReadWrite作为StreamReader的流来正确执行此操作,如其他几个答案herehere中所述

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

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),如果那会更好......

0 个答案:

没有答案