2016-09-26 123 views
1

我在C#中新的,和我在寫一些文本文件,爲了這個目的,我使用的是源代碼,我發現在谷歌搜索:爲什麼StreamWriter無法在c#中將文本寫入文件?

FileStream fs = System.IO.File.OpenWrite(Server.MapPath("~/FILE/") + logFile); 
StreamWriter sw = new StreamWriter(fs); 

//sw.Write(DateTime.Now.ToString() + " sent email to " + email); 
sw.Write(" sent email to "); 

fs.Close(); 

此代碼運行,但是當我打開文本文件時,我看不到任何數據,發生了什麼?我怎麼解決這個問題?

+0

嘗試https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx和https://www.google.com/#q=c-sharp+write+text+file –

+0

先關閉'sw'以確保它在你關閉'fs'之前刷新你所寫的內容,或者更好地將它們放入['using'語句中](https://msdn.microsoft.com/zh-cn/library/yh598w02的.aspx)。 – juharr

+0

@juharr我想作者會自動關閉這個不受限制的流。 – HimBromBeere

回答

1

修改你的代碼如下。希望你正在尋找這種類型。

using (FileStream fs = System.IO.File.OpenWrite(Server.MapPath("~/FILE/") + logFile)) 
{ 
    using (StreamWriter sw = new StreamWriter(fs)) 
    { 
     //sw.Write(DateTime.Now.ToString() + " sent email to " + email); 
     sw.Write(" sent email to "); 
    } 
    fs.Close(); 
} 
0

儘量簡單File.AppendAllText

File.AppendAllText(Path.Combine(Server.MapPath("~/FILE/"), logFile), 
    string.Format("{0} sent email to {1}", DateTime.Now, email)); 

附加日誌文件,而不是使用流和作家。

+0

謝謝,是有辦法解決我的代碼?我想用該代碼編寫。 –

+0

@behi behi:如果你的目標只是附加日誌文件,那麼'File.AppendAllText'會爲你做(打開流,編寫器,然後以適當的方式關閉項目)。 'FileStream'和'StreamWriter'只會給你的代碼帶來複雜性。流和寫作者是你必須通過條件,擦除,覆蓋等方式實現複雜代碼的方式。 –

+0

感謝我的朋友,你的權利,但在我的公司,我的老闆說只要寫下這個! –

相關問題