开发者

Keeping a log file under a certain size

开发者 https://www.devze.com 2023-04-04 01:29 出处:网络
I am keeping several text log files that I want to keep from growing too large. I searched for and found a lot of people asking the same thing and I found couple of solutions that looked like the effi

I am keeping several text log files that I want to keep from growing too large. I searched for and found a lot of people asking the same thing and I found couple of solutions that looked like the efficiency was questionable so I tried rolling my own function. I did the same thing previously in VB6 and ended up using the function in all my apps so I know I will be using it frequently now in my C# programs. This should probably be CW but since marking a question as CW is disabled I am posting it here. My question is, since I will be using this a lot is it efficient, and if not what should I change to improve it? Currently I am limiting the log files to 1MB and these are the largest logs I have kept so I don't anticipate them getting much if any larger.

private static void ShrinkFile(string file)
{
    StreamReader sr = new开发者_如何学JAVA StreamReader(file);
    for (int i = 0; i < 9; i++) // throw away the first 10 lines
    {
        sr.ReadLine();
    }
    string remainingContents = sr.ReadToEnd();
    sr.Close();
    File.WriteAllText(file, remainingContents);
}


beside suggesting you to use a proper logging framework like Log4Net or NLog (or any other), to improve your code you can at minimum make sure you always close the stream with a using:

private static void ShrinkFile(string file)
{
  using(var sr = new StreamReader(file))
  {
    for (int i = 0; i < 9; i++) // throw away the first 10 lines
    {
        sr.ReadLine();
    }

    // false here means to overwrite existing file.
    using (StreamWriter sw = new StreamWriter(file, false))
    {
      sw.Write(sr.ReadToEnd());
    }
  }
}

also I have avoided to do the ReadToEnd into a string because you can directly write into the StreamWriter.

0

精彩评论

暂无评论...
验证码 换一张
取 消