3

我有两个 C# 应用程序,一个是逐行读取文件(文件 A)并将其内容写入另一个文件(文件 B)。

第二个应用程序使用 FileSystemWatcher 来查看文件 B 的更新时间,并报告程序启动时间和文件更改时间之间的行号差异。

这就是我现在要做的所有事情,最终我想读取文件上次读取时间和当前读取时间之间的行,但直到我可以获得暂停的行差异。

我为应用程序 1 提供的代码是;

        static void Main(string[] args)
    {
        String line;

        StreamReader sr = new StreamReader("f:\\watch\\input.txt");

        FileStream fs = new FileStream("f:\\watch\\Chat.log", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
        StreamWriter sw = new StreamWriter(fs);

        while ((line = sr.ReadLine()) != null)
        {
            sw.WriteLine(line);
            Thread.Sleep(200);
            Console.WriteLine(line);
            sw.Flush();

        }

        sw.Close();
        sr.Close();

    }

我为应用程序 2 提供的代码是;

        public static int lines = 0;

    public static void Main()
    {
        Run();
    }

    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        if (args.Length != 2)
        {
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];

watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
   | NotifyFilters.FileName | NotifyFilters.DirectoryName;

watcher.Filter = "Chat.log";

watcher.Changed += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEvents = true;

lines = File.ReadAllLines(args[1] + "\\Chat.log").Length;

Console.WriteLine("File lines: " + lines);

while(Console.Read()!='q');
}

private static void OnChanged(object source, FileSystemEventArgs e)
{
    Linework(e.FullPath);
    Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

public static string Linework(string path)

{



   string newstring = " ";

using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    int newlines = File.ReadAllLines(path).Length;
    Console.WriteLine("Lines now: " + newlines);
}

return newstring;

}

现在,当我尝试同时运行这两个应用程序时,我收到一个异常消息“未处理的异常:System.IO.IOException:该进程无法访问该文件,因为它正在被另一个进程使用”。

我为 ReadWrite 访问设置了两个文件流,为 FileAccess.Write 设置了一个文件流,为 FileAccess.Read 设置了另一个。

关于为什么我会得到这个例外的任何线索?

谢谢休。

4

4 回答 4

7

行 = File.ReadAllLines(args[1] + "\Chat.log").Length;

有你的问题。该方法打开文件,读取所有行并再次关闭它。打开文件 FileShare.Read 时,它使用“正常”文件共享设置。这拒绝对也打开该文件的任何其他进程进行写访问。

这在这里行不通,您已经用写权限打开了文件。第二个过程不能否认它。结果是 IOException。

您不能在此处按原样使用 File.ReadAllLines(),您需要使用 FileShare.ReadWrite 打开 FileStream,将其传递给 StreamReader 并读取所有行。

当心您在这里遇到的非常麻烦的比赛潜力,不能保证您将阅读的最后一行是完整的一行。在行尾只得到一个 \r 而不是 \n 是一个特别棘手的问题。这将随机且不频繁地发生,是最难解决的错误。也许你的 Flush() 调用修复了它,我从来没有足够的勇气来测试它。

于 2010-07-06T19:41:27.107 回答
4

在这种情况下,允许第二个程序对文件进行读写访问将起作用。

//lines = File.ReadAllLines(args[1] + "\\Chat.log").Length;
//Commenting the above lines as this would again open a new filestream on the chat.log
//without the proper access mode required.


    using (FileStream fsReader = new FileStream(args[1] + "\\Chat.log", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using (StreamReader sr = new StreamReader(fsReader))
            {
                while (sr.ReadLine() != null)
                    lines++;
            }
        }
于 2010-07-06T18:35:21.280 回答
1

MSDN提供了两种不获取独占保留的方法:

当访问 SafeFileHandle 属性以公开句柄或 FileStream 对象在其构造函数中被赋予 SafeFileHandle 属性时,FileStream 对象将不会对其句柄进行独占保留。

该文档暗示反之亦然:

打开 FileStream 而不设置 SafeFileHandle 意味着 FileStream 保持对文件句柄的独占保留(这与应该抛出的 IO 异常内联)。

于 2010-07-06T18:28:01.100 回答
1
StreamReader sr = new StreamReader("f:\\watch\\input.txt");

input.txt 可能无法阅读?

在第一个应用程序中也使用该using语句而不是 Close() (以防引发异常)。

否则没关系。文件共享可能需要额外的权限(不能真正影响)。

我错过了一段代码:

int newlines = File.ReadAllLines(path).Length;

使用streamwith a StreamReader

于 2010-07-06T18:32:16.170 回答