2009-08-18 76 views
1
public void LoadRealmlist() 
{ 
    try 
    { 
     File.Delete(Properties.Settings.Default.WoWFolderLocation + 
      "Data/realmlist.wtf"); 

     StreamWriter TheWriter = 
      new StreamWriter(Properties.Settings.Default.WoWFolderLocation + 
      "Data/realmlist.wtf"); 

     TheWriter.WriteLine("this is my test string"); 
     TheWriter.Close(); 
    } 
    catch (Exception) 
    {  
    }    
} 

請問我的方法正確地刪除文件,然後創建一個以「realmlist.wtf」作爲名字,然後寫了一行呢?使用File.Delete刪除文件,然後使用Streamwriter創建相同的文件?

我有點困惑,因爲我看不到它實際上創建文件再次。或者創建StreamWriter的行爲是否會自動創建一個文件?

回答

3

的流寫入將創建文件,如果它不存在。 它將在構造函數創建它,所以當StreamWriter的實例化。

+0

要說清楚,我的Try()語句中的第二行將創建該文件? – 2009-08-18 03:08:07

+1

是的: 「StreamWriter TheWriter = new StreamWriter(Properties.Settings.Default.WoWFolderLocation +」Data/realmlist.wtf「); 」 – Russell 2009-08-18 03:09:01

+0

「我需要知道的,非常感謝! – 2009-08-18 03:13:13

1

您知道,如果您將FileStream實例傳遞給StreamWriter構造函數,則可以將其設置爲僅覆蓋該文件。只需將它與構造函數一起傳遞即可。

http://msdn.microsoft.com/en-us/library/system.io.filestream.filestream.aspx

例子:

try 
{ 
    using (FileStream fs = new FileStream(filename, FileMode.Create)) 
    { 
     //FileMode.Create will make sure that if the file allready exists, 
     //it is deleted and a new one create. If not, it is created normally. 
     using (StreamWriter sw = new StreamWriter(fs)) 
     { 
      //whatever you wanna do. 
     } 
    } 
} 
catch (Exception e) 
{ 
    System.Diagnostics.Debug.WriteLine(e.Message); 
} 

而且,有了這個,你將不再需要使用.Close方法。 using()函數爲你做。

0

嘗試System.IO.File.CreateText