2017-07-19 62 views
0
public partial class Form1 : Form 
{ 
    string path = [email protected]"C:\Journal"; 
    string fileName = @""; 
    string compact = ""; 
    public Form1() 
    { 
     InitializeComponent(); 
     fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt"; 
     compact = (path + @"\" + fileName);   
    } 

    private void btnWrite_Click(object sender, EventArgs e) 
    { 
     if(File.Exists(fileName)) 
     { 
      StreamWriter myWriter = new StreamWriter(compact, true); 
      myWriter.WriteLine(txtDisplay.Text); 
      myWriter.Close(); 
     } 
     else 
     { 
      StreamWriter myWriter = new StreamWriter(compact, true); 
      myWriter.WriteLine(txtDisplay.Text); 
      myWriter.Close(); 
     } 
} 

我正在嘗試使用每月日曆作爲文件名將文字從多行文本框寫入文件。我不斷收到目錄不存在的錯誤。不知道,因爲我在路徑中創建文件夾的原因,我感謝幫助。寫入文件,目錄錯誤

System.IO.DirectoryNotFoundException was unhandled 
+0

你會得到什麼錯誤? – maccettura

+6

看來'C:\ Journal'不存在。 'StreamWriter'可以創建一個新文件,但不能創建它的目錄 – litelite

+4

一個可能的原因是文件名中有'/'。你有沒有調試和檢查文件名變量的值? –

回答

0

看來,你必須創建目錄。另一個問題是

fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt"; 

因爲短日期時間格式可以包含在文件名中禁止'/''\'

public Form1() { 
    InitializeComponent(); 

    // ToString(...) we don't want/or \ in the file's name 
    fileName = monthCalendar1.SelectionRange.Start.ToString("dd'.'MM'.'yyyy") + ".txt"; 
    compact = Path.Combine(path, fileName);   
    } 

    private void btnWrite_Click(object sender, EventArgs e) { 
    Directory.CreateDirectory(Path.GetDirectoryName(compact)); 

    // Or File.AppendAllText(compact, txtDisplay.Text); 
    File.AppendAllLines(compact, new string[] {txtDisplay.Text}); 
    }