1

I am trying to create a file and save text, but it's only creating file can anyone suggest what the problem is?

private void button2_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Text File|*.txt";
        sfd.FileName = "Password";
        sfd.Title = "Save Text File";
        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string path = sfd.FileName;
            StreamWriter bw = new StreamWriter(File.Create(path));
            bw.Write(randomstring);
            bw.Dispose();
        }
    }
Peter Foti
  • 5,526
  • 6
  • 34
  • 47
Mik
  • 151
  • 3
  • 4
  • 14

4 Answers4

3

You need to call bw.Close() before calling bw.Dispose(). Per the API: "You must call Close to ensure that all data is correctly written out to the underlying stream." (http://msdn.microsoft.com/en-us/library/system.io.streamwriter.close(v=vs.110).aspx)

I'd actually change the code to:

using (StreamWriter bw = new StreamWriter(File.Create(path)))
{
    bw.Write(randomstring);
    bw.Close();
}

The using block will automatically call Dispose(), whether or not everything completes successfully.

musical_coder
  • 3,886
  • 3
  • 15
  • 18
2

Try and use File.WriteAllText instead

    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        //...
        File.WriteAllText(path, randomstring);
    }    
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
1
bw.Write(randomstring);
bw.Dispose();

You write something, then dispose of the object entirely. Try:

bw.Write(randomstring);
bw.Close();
bw.Dispose();
user3012708
  • 793
  • 1
  • 11
  • 33
0

Per the documentation, you need to call bw.Close() before you dispose of it. Also, you should use using to ensure that all IDisposables are properly disposed of.

if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = sfd.FileName;
    using (var fs = File.Create(path))
    using (StreamWriter bw = new StreamWriter(fs))
    {
        bw.Write(randomstring);
        bw.Close();
    }
}

Or just use File.WriteAllText:

if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = sfd.FileName;
    File.WriteAllText(path, randomstring);
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122