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

[亡魂溺海] 提交于 2019-12-02 13:05:11

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

StreamReader reader = new StreamReader(_fileStream);
List<String> logList = new List<String>();

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<String> lines = new List<String>();

        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);
}

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<string> 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<string> lines)
    {
        var sw = new StreamWriter(f);
        foreach(var line in lines)
        {
            sw.WriteLine(line);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!