Hi, I want to add text to an existing file. Note that I want to add it in different locations of the file, not just appending at the end.
I have tried the following in C#:
-----------------------------
FileStream myfile = new FileStream(myinputfile, FileMode.Open, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(myfile);
sw.BaseStream.Seek(0,SeekOrigin.Begin);
sw.WriteLine("Some test");
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("some other text");
sw.Flush();
sw.Close();
outfile.Close();
-----------------------------
Everything works fine except the writing to the beginning of file overwrites the existing contents.
My question is: How can add text to the file without overwriting existing contents? As I said earlier, I need to be able to add it anywhere in the file, not just at the end.
Thanks!
/Minh
I have tried the following in C#:
-----------------------------
FileStream myfile = new FileStream(myinputfile, FileMode.Open, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(myfile);
sw.BaseStream.Seek(0,SeekOrigin.Begin);
sw.WriteLine("Some test");
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("some other text");
sw.Flush();
sw.Close();
outfile.Close();
-----------------------------
Everything works fine except the writing to the beginning of file overwrites the existing contents.
My question is: How can add text to the file without overwriting existing contents? As I said earlier, I need to be able to add it anywhere in the file, not just at the end.
Thanks!
/Minh