Removing the first line of a text file in C#

前端 未结 5 400
眼角桃花
眼角桃花 2020-12-11 15:50

I can currently remove the last line of a text file using:

    var lines = System.IO.File.ReadAllLines(\"test.txt\");
    System.IO.File.WriteAllLines(\"test         


        
5条回答
  •  無奈伤痛
    2020-12-11 16:31

    Here is an alternative:

            using (var stream = File.OpenRead("C:\\yourfile"))
            {
                var items = new LinkedList();
                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 and don't want to waste memory you could do something like this:

        public static IEnumerable 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.
            }
        }
    

提交回复
热议问题