0

I've written a little program for myself that I use to read quite large log files (just plain text and numbers) and writing them out in a textbox (notepadish thingy).

I use this method for reading a file and while it does the trick I'm wondering if there's some way to optimize it and if the current file being read is locked out from being written to while reading it (since it's log files that's constantly being updated this is not good for me).

    private void ReadFile(string path)
    {
        using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (StreamReader reader = new StreamReader(file))
        {
            StringBuilder sb = new StringBuilder();
            string r = reader.ReadLine();

            while (r != null)
            {
                sb.Append(r);
                sb.Append(Environment.NewLine);
                r = reader.ReadLine();
            }
            textBox.Text = sb.ToString();
            reader.Close();
        }
    }
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
perkrlsn
  • 249
  • 3
  • 10

2 Answers2

1

I've found a couple suggestions at the question posted here, your code already confirms to the first suggestion, so I'd try using

File.OpenRead(path)

and see if that works for you.

And if it doesn't, than apparently the program that's writing to the file simply won't allow you to read it at all so long as it has a handle on it. You might notice the FileShare.ReadWrite which tells the system what other programs may do with the file, the program that's writing the log might not be allowing you to even read the file at all.

Community
  • 1
  • 1
0

Try this:

using System;
using System.IO;

namespace csharp_station.howto
{
    class TextFileReader
    {
        static void Main(string[] args)
        {
            // create reader & open file
            Textreader tr = new StreamReader("date.txt");

            // read a line of text
            Console.WriteLine(tr.ReadLine());

            // close the stream
            tr.Close();

            // create a writer and open the file
            TextWriter tw = new StreamWriter("date.txt");

            // write a line of text to the file
            tw.WriteLine(DateTime.Now);

            // close the stream
            tw.Close();
        }
    }
}

This would be the easiest way to do it. And I think your code lookes fine to me. I don't see a Problem by reading a log file into a textbox. You could try to do it simutanously by using threats....

ThatMSG
  • 1,456
  • 1
  • 16
  • 27