简体   繁体   中英

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.

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.

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. Remember to subtract the appropriate number of lines in the Take method. 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:

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 ):

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).

Here's a different approach that uses ArraySegment<string> instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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