0

Is it possible to create 2 applications that one always writes to file (like a log file) and other application that can read from a file?

I'd show you what I've tried:

Writter application

static void Main(string[] args)
    {
        string file = @"D:\filetest.txt";
        int i = 0;
        while (true)
        {

            using(FileStream fs = File.OpenWrite(file))
            {
                using(StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine($"line line {i++}");
                }
            }
            Thread.Sleep(500);
        }
    }

reader application

    static void Main(string[] args)
    {
        string file = @"D:\filetest.txt";
        int i = 0;
        while (true)
        {
            string lines = string.Empty;
            using (FileStream fs = File.OpenRead(file))
            {
                using (StreamReader sw = new StreamReader(fs))
                {
                     lines = sw.ReadToEnd();
                }
            }
            Console.WriteLine(lines);
            Thread.Sleep(200);
        }
    }

Of course as I expected I got exception on File.OpenWrite(file) line "he process cannot access the file 'D:\filetest.txt' because it is being used by another process."

The only solution I think is to copy the written file before reading it.

Rafaela Lourenço
  • 1,126
  • 16
  • 33
Izikon
  • 902
  • 11
  • 23
  • To ensure this isn't a XY Problem (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) can you take a step back and explain why you need this code? – mjwills Nov 22 '17 at 11:08
  • as i wrote its writing a log file the reading in this case will allow us to analyse the log file - i cant do anything in the writer application – Izikon Nov 22 '17 at 11:11
  • 1
    Use File.Open and allowing sharing – BugFinder Nov 22 '17 at 11:13
  • You may need to update the logic in the linked post a bit to not stop when you've reached the end of the file, assuming you want to read things as they're being written. – Bernhard Barker Nov 22 '17 at 11:15
  • @mjwills you provide me better solution the fileshare flag was the diffrent – Izikon Nov 22 '17 at 11:50

1 Answers1

0

The documentation for File.OpenWrite states:

Return Value Type: System.IO.FileStream An unshared FileStream object on the specified path with Write access.

You could consider using a shared FileStream:

using (FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.Read))

FileShare.Read will allow File.OpenRead to work.

mjwills
  • 23,389
  • 6
  • 40
  • 63