C# Insert text lines before a certain word

I currently have a app that creates lines of code and at the moment it uses File.AppendAllText(newPathName, sptData); File.AppendAllText(newPathName, string.Format("<0>", " ", Environment.NewLine)); to add those new lines to the bottom of the document. How can I get it to insert the data before the line with "PROC" you see below? Please note that the file will not always have the same data in but will always have the word PROC which is why it needs to be before that. !# ----------------------------------------------- !# ------ WOBJ DATA !# ----------------------------------------------- PERS wobjdata w_td97200:=[False,True,"",[[-854.99,1926.58,592.01],[0.737197,0,0,0.675677]],[[0,0,0],[1,0,0,0]]]; PERS wobjdata w_tc97200:=[False,True,"",[[-463.99,1486.54,229.27],[0.298836,0.640862,0.298836,-0.640852]],[[0,0,0],[1,0,0,0]]]; INSERT NEW TEXT HERE PROC P13_a_rsw01_200_l538com() !======== ! PROG_INFO : L538 STN200

asked Nov 29, 2017 at 12:47 40 7 7 bronze badges What about foreach loop? – user6416335 Commented Nov 29, 2017 at 12:53

1 Answer 1

var lines = File.ReadAllLines(@"C:\1.txt").ToList(); for (int i = 0; i < lines.Count; i++) < if (lines[i].StartsWith("PROC")) < lines.Insert(i, "NEW TEXT"); i++; >> 
answered Nov 29, 2017 at 12:51 user6416335 user6416335 Should be lines.Insert(i, "NEW TEXT"); to place the new line before the PROC line. Commented Nov 29, 2017 at 13:01

No, insert displaces the elements one, if you find the line at index 2 you want the new line to be at index 2 and the old at index 3. Else, think of this, you can't use a negative index, if you want to add before index 0 it would be impossible.