How can I remove the oldest lines in a file when using a FileStream and StreamWriter?

后端 未结 2 1221
误落风尘
误落风尘 2021-01-29 08:21

Based on Prakash\'s answer here, I thought I\'d try something like this to remove the oldest lines in a file prior to adding a new line to it:

private ExceptionL         


        
2条回答
  •  轮回少年
    2021-01-29 09:04

    ReadAllLines and WriteAllLines are just hiding a loop from you. Just do:

    StreamReader reader = new StreamReader(_fileStream);
    List logList = new List();
    
    while (!reader.EndOfStream)
       logList.Add(reader.ReadLine());
    

    Note that this is nearly identical to the implementation of File.ReadAllLines (from MSDN Reference Source)

           String line;
            List lines = new List();
    
            using (StreamReader sr = new StreamReader(path, encoding))
                while ((line = sr.ReadLine()) != null)
                    lines.Add(line);
    
            return lines.ToArray();
    

    WriteAllLines is simialr:

    StreamWriter writer = new StreamWriter(path, false); //Don't append!
    foreach (String line in logList)
    {
       writer.WriteLine(line);
    }
    

提交回复
热议问题