Reading file content changes in .NET

后端 未结 2 1834
难免孤独
难免孤独 2020-12-14 23:00

In Linux, a lot of IPC is done by appending to a file in 1 process and reading the new content from another process.

I want to do the above in Windows/.NET (Too mess

2条回答
  •  时光说笑
    2020-12-14 23:35

    You can store the offset of the last read operation and seek the file to that offset when you get a changed file notification. An example follows:

    Main method:

    public static void Main(string[] args)
    {
        File.WriteAllLines("test.txt", new string[] { });
    
        new Thread(() => ReadFromFile()).Start();
    
        WriteToFile();
    }
    

    Read from file method:

    private static void ReadFromFile()
    {
        long offset = 0;
    
        FileSystemWatcher fsw = new FileSystemWatcher
        {
            Path = Environment.CurrentDirectory,
            Filter = "test.txt"
        };
    
        FileStream file = File.Open(
            "test.txt",
            FileMode.Open,
            FileAccess.Read,
            FileShare.Write);
    
        StreamReader reader = new StreamReader(file);
        while (true)
        {
            fsw.WaitForChanged(WatcherChangeTypes.Changed);
    
            file.Seek(offset, SeekOrigin.Begin);
            if (!reader.EndOfStream)
            {
                do
                {
                    Console.WriteLine(reader.ReadLine());
                } while (!reader.EndOfStream);
    
                offset = file.Position;
            }
        }
    }
    

    Write to file method:

    private static void WriteToFile()
    {
        for (int i = 0; i < 100; i++)
        {
            FileStream writeFile = File.Open(
                "test.txt",
                FileMode.Append,
                FileAccess.Write,
                FileShare.Read);
    
            using (FileStream file = writeFile)
            {
                using (StreamWriter sw = new StreamWriter(file))
                {
                    sw.WriteLine(i);
                    Thread.Sleep(100);
                }
            }
        }
    }
    

提交回复
热议问题