$phinX Posted October 28, 2005 Share Posted October 28, 2005 I need to add a line of text to the top of a file in my C# app. I can create files ok, i can append to the end of files ok, but how do i insert a string at, say, line 1? Please help!! Link to comment https://www.neowin.net/forum/topic/390887-c-how-do-i-insert-a-string-to-top-of-text-file/ Share on other sites More sharing options...
0 kjordan2001 Posted October 28, 2005 Share Posted October 28, 2005 I'm not sure of the most efficient way, but this way works: string filename = "c:\\test.txt"; string entireFile = ""; if (File.Exists(filename)) { StreamReader reader = new StreamReader(filename); entireFile = reader.ReadToEnd(); reader.Close(); } StreamWriter writer = new StreamWriter(filename); writer.WriteLine("This line is pre-pended"); writer.Write(entireFile); writer.Close(); Link to comment https://www.neowin.net/forum/topic/390887-c-how-do-i-insert-a-string-to-top-of-text-file/#findComment-586736699 Share on other sites More sharing options...
0 benjeeeboy Posted October 28, 2005 Share Posted October 28, 2005 Instead of opening it using FileMode.Append, use FileMode.Open and I think it'll move stuff back but I'm not totally sure Link to comment https://www.neowin.net/forum/topic/390887-c-how-do-i-insert-a-string-to-top-of-text-file/#findComment-586737985 Share on other sites More sharing options...
0 Computer Guru Posted October 28, 2005 Share Posted October 28, 2005 benjeeeboy said: Instead of opening it using FileMode.Append, use FileMode.Open and I think it'll move stuff back but I'm not totally sure 586737985[/snapback] no, it wont work AFAIK The only way you can do it is to open the file, copy everything in there, add your text, then paste the stuff from before. so it would be somethin like what kjordan posted Link to comment https://www.neowin.net/forum/topic/390887-c-how-do-i-insert-a-string-to-top-of-text-file/#findComment-586738164 Share on other sites More sharing options...
Question
$phinX
I need to add a line of text to the top of a file in my C# app.
I can create files ok, i can append to the end of files ok, but how do i insert a string at, say, line 1?
Please help!!
Link to comment
https://www.neowin.net/forum/topic/390887-c-how-do-i-insert-a-string-to-top-of-text-file/Share on other sites
3 answers to this question
Recommended Posts