Search code examples
c#winformsstreamwriterfiledialog

Avoid exception when writing to null file


I'm doing some WPF exercises and I could succesfully write a file with content on it.

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
sfd.ShowDialog();
using (StreamWriter sw = File.CreateText(sfd.FileName))
{
  sw.Write(container.Text);
  sw.Close();
}
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();

That using (StreamWriter) is rising the exception.

If I try to save a file, but, close the window before informing a file name , things go bad.

How can I avoid that ? I tried checking if the file is null ( both above and inside the using statement but it still goes off.


Solution

  • You need to check the result of ShowDialog:

    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Text file (*.txt)|*.txt";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        File.WriteAllText(sfd.FileName, container.Text);
        MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
        container.ResetText();
    }