Removing the first line of a text file in C#

Instead of lines.Take, you can use lines.Skip, like:

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

to truncate at the beginning despite the fact that the technique used (read all text and write everything back) is very inefficient.

About the efficient way: The inefficiency comes from the necessity to read the whole file into memory. The other way around could easily be to seek in a stream and copy the stream to another output file, delete the original, and rename the old. That one would be equally fast and yet consume much less memory.

Truncating a file at the end is much easier. You can just find the trunaction position and call FileStream.SetLength().


Here is an alternative:

        using (var stream = File.OpenRead("C:\\yourfile"))
        {
            var items = new LinkedList<string>();
            using (var reader = new StreamReader(stream))
            {
                reader.ReadLine(); // skip one line
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    //it's far better to do the actual processing here
                    items.AddLast(line);
                }
            }
        }

Update

If you need an IEnumerable<string> and don't want to waste memory you could do something like this:

    public static IEnumerable<string> GetFileLines(string filename)
    {
        using (var stream = File.OpenRead(filename))
        {
            using (var reader = new StreamReader(stream))
            {
                reader.ReadLine(); // skip one line
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    yield return line;
                }
            }
        }
    }


    static void Main(string[] args)
    {
        foreach (var line in GetFileLines("C:\\yourfile.txt"))
        {
            // do something with the line here.
        }
    }

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

Skip eliminates the given number of elements from the beginning of the sequence. Take eliminates all but the given number of elements from the end of the sequence.

Tags:

Windows

C#

.Net