简体   繁体   English

在C#中保存文本文件

[英]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;
    }
}

You're checking the DialogResult property for your main form , but it's the child form that you want to check. 您正在检查DialogResult属性的主窗体 ,但它是您要检查的子窗体。 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. 另外,您应该像上面所做的那样将StreamWriter包装在using块中。 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. using块为语法糖try/finally块,其调用Dispose()后者又调用Close()在所述) finally部分。

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

You are creating the file before checking the result of the dialog. 您正在创建文件,然后检查对话框的结果。 Move the SaveFile variable bit into the "issaved = true" block. 将SaveFile变量位移到“ issaved = true”块中。

[edit] And as the others said, check the Dialog result properly [edit]正如其他人所说,请正确检查Dialog结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM