2015-08-31 101 views
0

我正在做一些WPF練習,我可以成功地編寫一個包含內容的文件。寫入空文件時避免異常

SaveFileDialog sfd = new SaveFileDialog(); 
sfd.Filter = "Text file (*.txt)|*.txt"; 
sfd.ShowDialog(); 
using (StreamWriter sw = File.CreateText(sfd.FileName)) 
{ 
    sw.Write(container.Text); 
    sw.Close(); 
} 
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString()); 
container.ResetText(); 

using (StreamWriter)是上升的例外。

如果我嘗試保存文件,但是在通知文件名之前關閉窗口,事情就會變糟。

我該如何避免這種情況?我試圖檢查,如果該文件是空(上方和using語句中,但它仍然熄滅

+0

請定義'事情bad' –

+0

閱讀SaveFileDialog.FileName的文檔。如果沒有選擇文件,它將是一個空字符串,而不是null:https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename( v = vs.110).aspx。 – Joe

回答

3

您需要檢查的ShowDialog的結果:。

SaveFileDialog sfd = new SaveFileDialog(); 
sfd.Filter = "Text file (*.txt)|*.txt"; 
if (sfd.ShowDialog() == DialogResult.OK) 
{ 
    File.WriteAllText(sfd.FileName, container.Text); 
    MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString()); 
    container.ResetText(); 
} 
+0

它表示操作符不能應用於操作數。=/ – Onilol

+0

您是使用WPF的SaveFileDialog(Microsoft.Win32.SaveFileDialog)還是使用WinForms的SaveFileDialog(System.Windows。 Forms.SaveFileDial OG)?如果你正在開發一個WPF應用程序,你應該使用WPF的,它返回一個可爲空的,這?操作員使用。 –

+0

我正在使用WinForms。 – Onilol