从文本文件中删除最后一行 [英] Strip the last line from a text file

查看:91
本文介绍了从文本文件中删除最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文本文件中删除最后一行.我知道如何在C#中打开和保存文本文件,但是如何去除文本文件的最后一行?

I need to strip the last line from a text file. I know how to open and save text files in C#, but how would I strip the last line of the text file?

文本文件的大小总是不同的(有些行有80行,有些行有20行).

The text file will always be different sizes (some have 80 lines, some have 20).

有人可以告诉我该怎么做吗?

Can someone please show me how to do this?

谢谢.

推荐答案

使用少量的行,您可以轻松地使用类似的东西

With a small number of lines, you could easily use something like this

string filename = @"C:\Temp\junk.txt";

string[] lines = File.ReadAllLines(filename);
File.WriteAllLines(filename, lines.Take(lines.Count() - 1));

但是,随着文件变大,您可能希望使用类似

However, as the files get larger, you may want to stream the data in and out with something like this

string filename = @"C:\Temp\junk.txt";
string tempfile = @"C:\Temp\junk_temp.txt";

using (StreamReader reader = new StreamReader(filename))
{                
    using (StreamWriter writer = new StreamWriter(tempfile))
    {
        string line = reader.ReadLine();

        while (!reader.EndOfStream)
        {
            writer.WriteLine(line);
            line = reader.ReadLine();
        } // by reading ahead, will not write last line to file
    }
}

File.Delete(filename);
File.Move(tempfile, filename);

这篇关于从文本文件中删除最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆