简体   繁体   中英

Editing specific lines in a text file using c#

I'm currently trying to edit a text file in c#. This text file is created in a previous form and consists of the following :

Date Of Birth = 01/01/1980
Age = 31
Total = 40985
required1 = 
required2 = 
required3 = 

This text file is only 13 lines long, basically i want to ignore the first three lines then edit the following 10 lines. I tried initially with the following code but the obvious flaw is appending to the file:

List<string> newlines = new List<string>();
newlines.Add(Convert.ToString(required1));
newlines.Add(Convert.ToString(required2));
newlines.Add(Convert.ToString(required3));

System.IO.File.AppendAllLines(filepath);

I'm thinking using streamreader reading all the lines but how to edit the 3rd line onwards is something of a mystery, yes I'm new using c# any help is greatly appreciated.

Since your file is small, you can load it whole into memory. Then work with that and save it, completely overwriting the whole file:

string[] lines = File.ReadAllLines(fileName);

// modify the lines

File.WriteAllLines(fileName, lines);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM