Although probably not a serious problem in this case, existing answers all rely on the first reading of the entire contents of the file in memory. For small files, this is probably good, but if you work with very large files, it can be prohibitive.
Itβs trivial to create the 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 list each line of a file without first buffering the entire file (per: fooobar.com/questions/96622 / ... ):
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 single-line file 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 (significantly) more code than other answers that have already been posted here, but should work with files of almost any size (as well as providing code for a potentially useful SkipLast extension SkipLast ).
source share