2013-08-27 85 views
4

我的程序:檢查Settings.txt文件。如果文件不存在,請創建文本並自動寫入。如果Settings.txt文件已經存在,則忽略。不要在現有文件中創建或寫入。文件創建但不能寫入

我的問題:當文件不存在時,Settings.txt文件創建但它是空的。我希望程序在創建文件時寫入它。謝謝你的幫助。

private void Form1_Load(object sender, EventArgs e) 
    { 
     string path = @"C:\Users\Smith\Documents\Visual Studio 2010\Projects\Ver.2\Settings.txt"; 
     if (!File.Exists(path)) 
     { 
      File.Create(path); 
      TextWriter tw = new StreamWriter(path); 
      tw.WriteLine("Manual Numbers="); 
      tw.WriteLine(""); 
      tw.WriteLine("Installation Technical Manual: "); 
      tw.WriteLine("Performance Manual: "); 
      tw.WriteLine("Planned Maintenance Technical Manual: "); 
      tw.WriteLine("Service Calibration Manual: "); 
      tw.WriteLine("System Information Manual: "); 
      tw.WriteLine(""); 
      tw.Close(); 
     } 
    } 

回答

5

以下是我認爲發生的事情。當我複製並運行你的代碼時,拋出了一個異常。這可能是因爲您創建文件兩次並且在第二次創建之前不要關閉它。

僅供參考,TextWriter tw = new StreamWriter(path);爲您創建文件。你不需要調用File.Create

和後續運行過程中,我不認爲你刪除的文件,因爲文件已經存在,if (!File.Exists(path))永遠不會滿意,而且整個if語句將被跳過

這裏

  • 因此,有多個點擺脫File.Create呼叫
  • 的,如果你想要的文件被覆蓋,你不應該檢查它是否存在,你應該只是簡單地覆蓋。
+0

Yupp!現在正在工作。謝謝你的幫助。 :) – Smith

14

嘗試這種情況:

using(FileStream stream = File.Create(path)) 
    { 
     TextWriter tw = new StreamWriter(stream); 
     tw.WriteLine("Manual Numbers="); 
     tw.WriteLine(""); 
     tw.WriteLine("Installation Technical Manual: "); 
     tw.WriteLine("Performance Manual: "); 
     tw.WriteLine("Planned Maintenance Technical Manual: "); 
     tw.WriteLine("Service Calibration Manual: "); 
     tw.WriteLine("System Information Manual: "); 
     tw.WriteLine(""); 
    } 

使用確保FILESTREAM關閉(設置),甚至當一個異常寫入內發生。

+2

的StreamWriter還需要處置。 –

+0

它現在正在工作!謝謝:) – Smith

+0

它不是nessesary,因爲我擁有這個流並且自己處置它。之後,我不喜歡StreamWriter的Dispose,因爲它正在關閉文件流。 (可能不需要) –

8

問題是File.Create返回一個FileStream,因此它將文件打開。您需要在TextWriter中使用FileStream。您還需要在使用(...)語句中調用FileStream或在FileStream上手動調用Dispose(),以確保文件在處理完畢後關閉。

+4

並將其包圍在使用塊中,或手動處理流也是一件好事。 – Oscar

2

雖然我很長一段時間後回答,但我想我應該回答

using (TextWriter tw = new StreamWriter(path)) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("Manual Numbers="); 
    sb.Append(Environment.NewLine); 
    sb.Append("Installation Technical Manual: "); 
    sb.Append("Performance Manual: "); 
    sb.Append("Planned Maintenance Technical Manual: "); 
    sb.Append("Service Calibration Manual: "); 
    sb.Append("System Information Manual: "); 
    sb.Append(Environment.NewLine); 
    tw.Write(sb.ToString()); 
} 
+0

謝謝!非常感激 :) – Smith