How to remove the first and last line from a C # text file?

I found this code in stackoverflow to remove the first and last line from a text file.

But I don’t understand how to combine this code into one so that it deletes the 1st and last line from one file?

I tried using streamreader to read the file, and then skip the 1st and last line, then the streamwriter to write to the new file, but could not get the correct structure.

Delete the first line.

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

to delete the last line.

  var lines = System.IO.File.ReadAllLines("..."); System.IO.File.WriteAllLines("...", lines.Take(lines.Length - 1).ToArray()); 
+6
source share
3 answers

You can link Skip and Take methods. Remember to subtract the appropriate number of lines in the Take method. The more you skip at the beginning, the fewer lines will remain.

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

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

+4
source

Here, a different approach is used, which uses ArraySegment<string> instead:

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

Source: https://habr.com/ru/post/947983/


All Articles