简体   繁体   English

如何从文本文件c#中删除第一行和最后一行?

[英]How to delete first and last line from a text file c#?

I found this code on stackoverflow to delete first and last line from a text file. 我在stackoverflow上发现了这个代码,用于删除文本文件中的第一行和最后一行。

But I'm not getting how to combine this code into one so that it will delete 1st and last line from a single file? 但我没有得到如何将这个代码组合成一个,以便它将从一个文件中删除第一行和最后一行?

What I tried was using streamreader read the file and then skip 1st and last line then streamwriter to write in new file, but couldn't get the proper structure. 我尝试使用streamreader读取文件,然后跳过第1行和最后一行,然后使用streamwriter写入新文件,但无法获得正确的结构。

To delete first line. 删除第一行。

var lines = System.IO.File.ReadAllLines("test.txt");
System.IO.File.WriteAllLines("test.txt", lines.Skip(1).ToArray());

to delete last line. 删除最后一行。

   var lines = System.IO.File.ReadAllLines("...");
System.IO.File.WriteAllLines("...", lines.Take(lines.Length - 1).ToArray());

You can chain the Skip and Take methods. 您可以链接SkipTake方法。 Remember to subtract the appropriate number of lines in the Take method. 记得在Take方法中减去适当的行数。 The more you skip at the beginning, the less lines remain. 您在开头跳过的越多,剩余的线越少。

var filename = "test.txt";
var lines = System.IO.File.ReadAllLines(filename);
System.IO.File.WriteAllLines(
    filename, 
    lines.Skip(1).Take(lines.Length - 2)
);

Whilst probably not a major issue in this case, the existing answers all rely on reading the entire contents of the file into memory first. 虽然在这种情况下可能不是主要问题,但现有的答案都依赖于首先将文件的全部内容读入内存。 For small files, that's probably fine, but if you're working with very large files, this could prove prohibitive. 对于小文件,这可能没问题,但是如果你使用的是非常大的文件,这可能会让人望而却步。

It is reasonably trivial to create a SkipLast equivalent of the existing Skip Linq method: 创建SkipLast相当于现有的Skip Linq方法是相当简单的:

public static class SkipLastExtension
{
    public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source, int count)
    {
        var queue = new Queue<T>();
        foreach (var item in source)
        {
            queue.Enqueue(item);
            if (queue.Count > count)
            {
                yield return queue.Dequeue();
            }
        }
    }
}

If we also define a method that allows us to enumerate over each line of a file without pre-buffering the whole file (per: https://stackoverflow.com/a/1271236/381588 ): 如果我们还定义了一个方法,允许我们枚举文件的每一行而不预先缓冲整个文件(per: https//stackoverflow.com/a/1271236/381588 ):

static IEnumerable<string> ReadFrom(string filename)
{
    using (var reader = File.OpenText(filename))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

Then we can use the following the following one-liner to write a new file that contains all the lines from the original file, except the first and last: 然后我们可以使用下面的一行代码来编写一个新文件,其中包含原始文件中的所有行,除了第一个和最后一行:

File.WriteAllLines("output.txt", ReadFrom("input.txt").Skip(1).SkipLast(1));

This is undoubtedly (considerably) more code than the other answers that have already been posted here, but should work on files of essentially any size, (as well as providing a code for a potentially useful SkipLast extension method). 这无疑是(相当多)代码已经在此处发布的其他答案,但应该适用于基本上任何大小的文件,(以及为潜在有用的SkipLast扩展方法提供代码)。

Here's a different approach that uses ArraySegment<string> instead: 这是使用ArraySegment<string>的另一种方法:

var lines = File.ReadAllLines("test.txt");
File.WriteAllLines("test.txt", new ArraySegment<string>(lines, 1, lines.Length-2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM