2
private void button2_Click(object sender, EventArgs e)
{        
    SaveFileDialog Sdialog = new SaveFileDialog();  
    Sdialog.ShowDialog();
    Sdialog.FileOk += Sdialog_FileOk;            
}

void Sdialog_FileOk(object sender, CancelEventArgs e)
{
    try
    {            
        StreamWriter FileProtocol = new StreamWriter(((SaveFileDialog)sender).FileName);
        FileProtocol.Write(textBox3.Text);
        FileProtocol.Close();
        MessageBox.Show("File is write ok");
    }
    catch (Exception)
    {
        MessageBox.Show("Unknown Error. File is not write");
    }
}

为什么事件 FileOk 不起作用?

4

1 回答 1

8

Because you need to hook the event up before calling ShowDialog(). When you call ShowDialog() it stops processing on that thread and waits for a response.

So, instead of this:

Sdialog.ShowDialog();
Sdialog.FileOk += Sdialog_FileOk;

do this:

Sdialog.FileOk += Sdialog_FileOk;
Sdialog.ShowDialog();

To use the DialogResult to simplify you're workflow, just do this:

if (Sdialog.ShowDialog() == DialogResult.OK)
{
    try
    {            
        StreamWriter FileProtocol =
            new StreamWriter(Sdialog.FileName);
        FileProtocol.Write(textBox3.Text);
        FileProtocol.Close();
        MessageBox.Show("File is write ok");
    }
    catch (Exception)
    {
        MessageBox.Show("Unknown Error. File is not write");
    }
}

ALSO: instead of doing this:

StreamWriter FileProtocol =
    new StreamWriter(Sdialog.FileName);
FileProtocol.Write(textBox3.Text);
FileProtocol.Close();

how about simplify it to this:

File.AppendAllText(Sdialog.FileName, textBox3.Text);

The benefit is two fold:

  • The code is clearly much more concise, and;
  • The code is safer because it manages the un-managed resources appropriately for you.
于 2013-10-07T18:50:27.137 回答