Search code examples
c#filefilestream

Filestream.write does not work


I used the following code to write on *.txt file, but nothing happens. Even, there is no exception.

        FileStream fs = new FileStream(@"D:\file.txt",FileMode.OpenOrCreate,FileAccess.Write,FileShare.None);    //Creating a stream with certain features to a file

        StreamWriter writer = new StreamWriter(fs);    //Use the fs to write

      //  writer.WriteLine(Text.Text);  none of the following methods works
        writer.Write("aaaaaaaaaaaa");

        fs.Close();

Thanks


Solution

  • Try to enclose it in a using block like this:

    using ( FileStream fs = new FileStream(@"D:\file.txt",FileMode.OpenOrCreate,FileAccess.Write,FileShare.None))
    using (StreamWriter fw = new StreamWriter(fs))
    {
        fw.Write("aaaaaaaaaaaa");
    } 
    

    A StreamWriter buffers data before writing it to the underlying stream. You need to flushes the buffer by disposing the StreamWriter