0

I have a text file (filename.txt) and I want to delete everything in this file from a special row number to the end of the text file.

How can I do this?
Is it even possible?

P.S.:
The number of the line is not constant.
It depends on the value of another variable in my code.

zx485
  • 28,498
  • 28
  • 50
  • 59
  • 1
    Read the file up to that line, count how far through the file you are in bytes, then [truncate](https://stackoverflow.com/questions/6537926/how-to-truncate-a-file-in-c) to that size – Nick is tired Sep 09 '18 at 14:11
  • Read the file till the row and then rewrite everything overwriting the old file. How many lines are present in the file? – Steve Sep 09 '18 at 14:11
  • 2
    See this post: https://stackoverflow.com/questions/21966607/extracting-the-first-10-lines-of-a-file-to-a-string – PiJei Sep 09 '18 at 14:13

1 Answers1

0

You can do the following:

  1. Read the count of lines which you need.
  2. Delete the file.
  3. Write your lines to a newly created file with the same path and name.

Below is an example of the code:

using System.IO;
using System.Collections.Generic;

namespace ConsoleApp3
{
    public class Program
    {
        static void Main(string[] args)
        {
            int lineNumber = 4;
            string filePath = @"C:\Users\Admin\Desktop\test - Copy.txt";
            List<string> lines = new List<string>();
            using (TextReader tr = new StreamReader(filePath))
            {
                int i = 0;
                while(i!=lineNumber)
                {
                    lines.Add(tr.ReadLine());
                    i++;
                }
            }
            File.Delete(filePath);
            File.WriteAllLines(filePath,lines);
        }
    }
}
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
  • this is quite inefficient because a) you just read all lines to memory b) you just did so iterating when you can just do `File.ReadAllLines()` – zaitsman Sep 09 '18 at 14:52
  • @zaitsman are you saying that reading for example 10 or even 1900 lines from 2000 lines is less efficient than reading all lines? – Samvel Petrosov Sep 09 '18 at 14:54