2015-10-20 50 views
2

我試圖做一個簡單的Windows窗體應用程序來保存一個文本文件。我在與下面的程序麻煩,它給了我:SaveFileDialog錯誤

空路徑是不合法的

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(); 
     } 
    } 
} 

回答

1

因爲你沒有「秀」 SaveFileDialog然而,這樣的文件名是空的。

嘗試向上移動的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); 
     } 
    } 
+0

這對我工作謝謝你太多了:) –

1

你應該換行書寫的語句如下所示。

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