2013-05-13 70 views
2

我使用StreamWriter寫入記事本中的東西。而且我發現我是否不使用陳述並單獨使用StreamWriter。該方法無法運行。有人知道原因嗎?c#使用語句和StreamWriter

static void Main(string[] args) 
    { 
     //StreamWriter c = new StreamWriter(@"C:\Users\rxxx\Desktop\important.txt", true); 
     using (StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true)) 
     { 
      c.WriteLine("hello"); 
     } 

這可以運行。但是,如果我運行標記的部分。記事本什麼也沒有顯示。

有人知道原因嗎?

+0

謝謝大家!你們是非常有幫助的。 Msdn的英語對我來說太過簡單和簡潔。很高興在這裏尋求幫助。再次感謝。 – martin 2013-05-14 01:14:37

回答

5

因爲當你使用,這是很好的做法使用對象,它調用Dispose方法和StreamWriter的的情況下,它調用Fush的對象,以及這將導致要寫入的數據在文件中。 using語句是「確保」的範圍對象將被處理完畢[MSDN]

var c = new StreamWriter(@"C:\Test\important.txt", true); 
c.AutoFlush = true; 
c.WriteLine("hello"); 
c.Dispose(); 
1
StreamWriter c = new StreamWriter(@"C:\Users\rxxx\Desktop\important.txt", true); 
// you need to write something to see 
c.WriteLine("hello"); 

如果使用using statement它會自動處理StreamWriter對象。但是,如果您沒有使用語句,則需要手動執行處理StreamWriter對象。在這種情況下,即使在異常情況下也要確保正確地處理對象。所以你可以做如下

StreamWriter c =null; 
try 
{ 
    c = new StreamWriter(fileFullPath, true); 
    c.WriteLine("hello"); 
} 
finally 
{ 
    if (c!= null) 
     c.Close(); 
} 
0

:你可以寫你的代碼,這樣http://msdn.microsoft.com/en-us/library/yh598w02.aspx

using (StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true)) 
{ 
    c.WriteLine("hello"); 
} 

如果不使用語句中使用,我仍然推薦使用try語句

try 
{ 
    StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true); 
} 
finally 
{ 
    c.Close(); 
} 
0

如果不使用using語句,程序不會將數據從緩衝區中清除到文件中。這就是爲什麼當您在記事本中打開「hello」時沒有寫入該文件。你可以明確地刷新緩衝區,以您的數據寫入文件:

StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true) 
c.WriteLine("hello"); 
c.Flush(); 

不過,你仍然需要處理的數據流。但是如果你使用Dispose()方法,它會自動刷新緩衝區(通過調用Flush()方法),所以你不需要使用Flush()!

通過使用'using'語句,不僅可以刷新緩衝區,還可以正確釋放流,而且不需要明確寫入Dispose()。這是做到這一點的最佳方式。