docxx
docxx

Reputation: 93

saving text file in C#

I am trying to write notepad, how do I know if user clicked 'Cancel'? My code doesn't work:

private void SaveAsItem_Click(object sender, EventArgs e)
{
    saveFileDialog1.FileName = "untitled";
    saveFileDialog1.Filter = "Text (*.txt)|*.txt";
    saveFileDialog1.ShowDialog();
    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
    SaveFile.WriteLine(richTextBox1.Text);
    SaveFile.Close();
    if (DialogResult == DialogResult.Cancel)
    {
        richTextBox1.Text = "CANCEL";
        issaved = false;
    }
    else
    {
        issaved = true;
    }
}

Upvotes: 1

Views: 2043

Answers (3)

Ed Swangren
Ed Swangren

Reputation: 124622

You're checking the DialogResult property for your main form, but it's the child form that you want to check. So...

var dr = saveFileDialog1.ShowDialog();
if( dr == DialogResult.OK )
{
    using(var SaveFile = new StreamWriter(saveFileDialog1.FileName))
    {
        SaveFile.WriteLine(richTextBox1.Text);
        issaved = true;
    }
}
else  // cancel (or something else)
{
    richTextBox1.Text = "CANCEL"; 
    issaved = false;      
}

Also, you should wrap your StreamWriter in a using block as I have done above. Your code will fail to close the file if an exception occurs. A using block is syntactic sugar for a try/finally block which calls Dispose() (which in turn calls Close()) in the finally portion.

Upvotes: 4

kprobst
kprobst

Reputation: 16651

DialogResult res = saveFileDialog1.ShowDialog();
if (res == DialogResult.Cancel) {
    // user cancelled
}
else {
    // Write file to disk using the filename chosen by user
}

Upvotes: 1

Peter Wishart
Peter Wishart

Reputation: 12270

You are creating the file before checking the result of the dialog. Move the SaveFile variable bit into the "issaved = true" block.

[edit] And as the others said, check the Dialog result properly

Upvotes: 0

Related Questions