Best way to read in a sliding log file in .NET?

I need to read in a sliding log file in .NET 3.5sp1. I am wondering what is the best way to do this? A file can get really big. The idea I had was

  • Open file
  • Read the file for the last line of reading (in the first case it was 0)
  • Read all remaining lines
  • Close the stream and remember the last line number.
  • Wait a bit.
  • Rinse / repeat.

I'm not sure if this is the best way, albeit memory efficient, given that the file can be quite huge. And I can not lock the log file :(

Thoughts?

+3
source share
3 answers

. . FileStream Length, read .

. , .
0

Watcher FileSystem , :

http://www.codeproject.com/KB/cs/wintail.aspx

, (). . , .

ReadOnly, , , .

+1

, , ?

    Object mLogLock = new Object(); //to make logging thread safe
    string mLogFile = ""; //set your log location
    string mLogDirectory = "";
    public void HandleMessage(string inMessage)
    {

        lock (mLogLock)
        {
            if (!System.IO.Directory.Exists(mLogDirectory ))
            {
                System.IO.Directory.CreateDirectory(mLogDirectory );
            }

            String theMessage = DateTime.Now.ToString("s");
            if (inMessage != null)
                theMessage += " : " + inMessage;

            StreamWriter sw = new StreamWriter(mLogFile, true);

            sw.WriteLine(theMessage );

            sw.Dispose();
            sw.Close();
        }
    }

, , - - , , . . , /, , , , .

, , MemoryStream, StreamWriter, ( ) MemoryStream. MemoryStream, . ?

0
source

All Articles