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

后端 未结 2 1202
误落风尘
误落风尘 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:16

    I would write simple extension methods for this, that do the job lazily without loading whole file to memory.

    Usage would be something like this:

    outfile.MyWriteLines(infile.MyReadLines().Skip(1));
    

    public static class Extensions
    {
        public static IEnumerable MyReadLines(this FileStream f)
        {
            var sr = new StreamReader(f);
    
            var line = sr.ReadLine();
            while (line != null)
            {
                yield return line;
                line = sr.ReadLine();
            }
        }
    
        public static void MyWriteLines(this FileStream f, IEnumerable lines)
        {
            var sw = new StreamWriter(f);
            foreach(var line in lines)
            {
                sw.WriteLine(line);
            }
        }
    }
    

提交回复
热议问题