Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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());
like image 299
Vishwanath Dalvi Avatar asked Jun 24 '13 11:06

Vishwanath Dalvi


2 Answers

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)
);
like image 92
Dennis Traub Avatar answered Oct 25 '22 14:10

Dennis Traub


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

like image 32
Iridium Avatar answered Oct 25 '22 13:10

Iridium