C#,从菜单栏保存,另存为按钮

时间:2018-10-16 15:33:30

标签: c# winforms

我正在尝试将富文本框内容保存到文件中。但是,当我尝试保存新文件时出现错误。另存为按预期方式。有什么建议么。谢谢

System.ArgumentException: 'Empty path name is not legal.'

我的“另存为”按钮的代码如下:

OpenFileDialog file_open = new OpenFileDialog();
 private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            string filename = "";

            // To filter files from SaveFileDialog
            saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
            saveDlg.DefaultExt = "*.rtf";
            saveDlg.FilterIndex = 1;
            saveDlg.Title = "Save the contents";

            filename = file_open.FileName;

            RichTextBoxStreamType stream_type;
            // Checks the extension of the file to save
            if (filename.Contains(".txt"))
                stream_type = RichTextBoxStreamType.PlainText;
            else
                stream_type = RichTextBoxStreamType.RichText;

            richTextBox1.SaveFile(filename, stream_type);




        }

 private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            string filename = "";

            // To filter files from SaveFileDialog
            saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
            saveDlg.DefaultExt = "*.rtf";
            saveDlg.FilterIndex = 1;
            saveDlg.Title = "Save the contents";

            DialogResult retval = saveDlg.ShowDialog();
            if (retval == DialogResult.OK)
                filename = saveDlg.FileName;
            else
                return;

            RichTextBoxStreamType stream_type;
            if (saveDlg.FilterIndex == 2)
                stream_type = RichTextBoxStreamType.PlainText;
            else
                stream_type = RichTextBoxStreamType.RichText;

            richTextBox1.SaveFile(filename, stream_type);
            MessageBox.Show("File Saved");
        }

0 个答案:

没有答案