Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write to beginning of file with Stream Writer?

Tags:

c#

stream

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 ?

like image 713
Hamed Avatar asked Sep 08 '12 19:09

Hamed


1 Answers

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);
        }
like image 105
competent_tech Avatar answered Sep 28 '22 10:09

competent_tech