Search code examples
c#filestreamstreamwriterfile-writing

How can i Rewrite File instead of appending using StreamWriter and file stream


I want to rewrite text file using StreamWriter. but when StreamWriter uses stream (like following code), the text will append to file.

StreamWriter sw = new StreamWriter(fstream);
sw.Write(text);
sw.Close();

i must use Stream in code because of that file share limitation


Solution

  • FileMode.Create ll create a new file. If the file excists, it ll show exception. Use FileMode.Truncate.

     string txt="your text";
        using (FileStream fs = new FileStream(@"C:\Users\rajesh.kumar\Desktop\test123.txt", FileMode.Truncate))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.Write("txt");
            }
        }