I want to insert my string to the beginning of the file. But there is no function to append in beginning in stream writer. So how should I do that ?
My code is :
string path = Directory.GetCurrentDirectory() + "\\test.txt";
StreamReader sreader = new StreamReader(path);
string str = sreader.ReadToEnd();
sreader.Close();
StreamWriter swriter = new StreamWriter(path, false);
swriter.WriteLine("example text");
swriter.WriteLine(str);
swriter.Close();
But it doesn't seem optimized. So is there any other way ?
You are almost there:
string path = Directory.GetCurrentDirectory() + "\\test.txt";
string str;
using (StreamReader sreader = new StreamReader(path)) {
str = sreader.ReadToEnd();
}
File.Delete(path);
using (StreamWriter swriter = new StreamWriter(path, false))
{
str = "example text" + Environment.NewLine + str;
swriter.Write(str);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With