SaveFileDialog Error

本文关键字:Error SaveFileDialog | 更新日期: 2023-09-27 18:18:37

我想做一个简单的Windows窗体应用程序,保存一个文本文件。我在执行下面的程序时遇到了问题,它告诉我:

空路径不合法

namespace Filing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void button_Save_Click(object sender, EventArgs e)
        {
            SaveFileDialog file = new SaveFileDialog();
            file.Filter = "Text (*.txt) | Word File *.doc";
            file.Title = "Save a file";
            File.WriteAllText(file.FileName, richTextBox1.Text);
            file.ShowDialog();
        }
        private void button_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

SaveFileDialog Error

因为你还没有"show" SaveFileDialog,所以fileName是空的。

尝试将showDialog向上移动:

private void button_Save_Click(object sender, EventArgs e)
    {
        SaveFileDialog file = new SaveFileDialog();
        file.Filter = "Text (*.txt) | Word File *.doc";
        file.Title = "Save a file";
        //Ask the user to select the file path and file name, don't forget to handle cancel button!
        if(file.ShowDialog() != DialogResult.Cancel)
        {
              File.WriteAllText(file.FileName, richTextBox1.Text);
        }
    }

您应该像下面这样包装写语句:

if(file.ShowDialog()== DialogResult.OK)
     File.WriteAllText(file.FileName, richTextBox1.Text);