c# - Add a new line at a specific position in a text file. -
i trying add specific line of text in file. between 2 boundaries.
an example of if wanted add line in between boundaries of item1:
[item1] 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 7 //add line here in between specific boundaries [/item1] [item2] 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 8 2550 coins 995 200000 7 2550 coins 995 200000 7 [/item2] [item3] 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 7 2550 coins 995 200000 7 [/item3]
this have tried far, near correct. keeps saying file being used reader cant edited writer, when did work cleared entire document.
public void createentry(string npcname) { string line; string filename = "drops.de"; streamwriter streamwriter = new streamwriter(filename); streamreader streamreader = new streamreader(filename); line = streamreader.readline(); if (line == ("[" + npcname + "]")) { streamreader.readline(); streamwriter.writeline("test"); } }
i know how write lines @ end of document.
this add line want it. (make sure have using system.io;
added)
public void createentry(string npcname) { //npcname = @"[/item1]"; <-- note '/'. string linetoadd = "//add line here in between specific boundaries"; string filename = "test.txt"; list<string> txtlines = new list<string>(); //fill list<string> lines txt file. foreach (string str in file.readalllines(filename)) { txtlines.add(str); } //insert line want add last under tag 'item1'. txtlines.insert(txtlines.indexof(npcname), linetoadd); //clear file. using block close connection immediately. using (file.create(filename)) { } //add lines including new one. foreach (string str in txtlines) { file.appendalltext(filename, str + environment.newline); } }
two year update: highest voted answer wrote 2 years ago , use improvements. i'm doing strange things in above method , want provide better alternative future readers.
public void createentry(string npcname) //npcname = "item1" { var filename = "test.txt"; var endtag = string.format("[/{0}]", npcname); var linetoadd = "//add line here in between specific boundaries"; var txtlines = file.readalllines(filename).tolist(); //fill list lines txt file. txtlines.insert(txtlines.indexof(endtag), linetoadd); //insert line want add last under tag 'item1'. file.writealllines(filename, txtlines); //add lines including new one. }