Does anyone have a quick code example for inserting text into the middle of a text file? I've tried everything I've found on google with no luck. Most people say do something like the following:
// get the file contents from our position to end of file
string fileBottom;
StreamReader sr = new StreamReader("c:\\temp\\test.txt");
sr.BaseStream.Seek(5, SeekOrigin.Begin);
fileBottom = sr.ReadToEnd();
sr.Close();
// open the file, seek to our position, append our text, append bottom of file
StreamWriter sw = new StreamWriter("c:\\temp\\test.txt");
sw.BaseStream.Seek(5, SeekOrigin.Begin);
sw.Write("MYTEXT");
sw.Write(fileBottom);
sw.Close();
The only problem with this is that the resulting file comes out completely blank up to the seek point, then "MYTEXT", then the remainder of the file. What am I missing here?
// get the file contents from our position to end of file
string fileBottom;
StreamReader sr = new StreamReader("c:\\temp\\test.txt");
sr.BaseStream.Seek(5, SeekOrigin.Begin);
fileBottom = sr.ReadToEnd();
sr.Close();
// open the file, seek to our position, append our text, append bottom of file
StreamWriter sw = new StreamWriter("c:\\temp\\test.txt");
sw.BaseStream.Seek(5, SeekOrigin.Begin);
sw.Write("MYTEXT");
sw.Write(fileBottom);
sw.Close();
The only problem with this is that the resulting file comes out completely blank up to the seek point, then "MYTEXT", then the remainder of the file. What am I missing here?
