2012-10-10 86 views
0

我有這個按鈕的單擊事件:如何將每次寫入文本文件而不重複創建(新建)?

private void button6_Click(object sender, EventArgs e) 
{ 
    if (File.Exists(@"d:\Keywords.txt")) 
    { 
     Dictionary<string,string> test = new Dictionary<string,string>(); 
     string value_of_each_key; 
     string key_of_each_line; 
     string line; 
     int index; 
     sr = new StreamReader(@"d:\Keywords.txt"); 
     while (null != (line = sr.ReadLine())) 
     { 
      index = line.IndexOf(","); 
      key_of_each_line = line.Substring(0, index); 
      value_of_each_key = line.Substring(index + 1); 
      test.Add(key_of_each_line, value_of_each_key); 
     } 
     sr.Close(); 
    } 

    using (var w = new StreamWriter(@"D:\Keywords.txt")) 
    { 
     crawlLocaly1 = new CrawlLocaly(); 
     crawlLocaly1.StartPosition = FormStartPosition.CenterParent; 
     DialogResult dr = crawlLocaly1.ShowDialog(this); 
     if (dr == DialogResult.OK) 
     { 
      if (LocalyKeyWords.ContainsKey(mainUrl)) 
      { 
       LocalyKeyWords[mainUrl].Clear(); 
       //probably you could skip this part and create new List everytime 
       LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText()); 
      } 
      else 
      { 
       LocalyKeyWords[mainUrl] = new List<string>(); 
       LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText()); 
      } 
      foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords) 
      { 
       w.WriteLine(kvp.Key + "," + string.Join(",", kvp.Value)); 
      } 
     } 
    } 
} 

文本文件的讀取工作好(做了一個測試,現在和它的工作好)。 Thep roblem是,每次我點擊按鈕它也將創建一個新的文本文件,我想要的是,當我點擊按鈕的文本文件將準備添加一個新的文本給他,而不是創建每一次新的一個。

我該如何解決這個問題?

回答

5

這聽起來像你只是想改變這一點:

new StreamWriter(@"D:\Keywords.txt") 

要這樣:

new StreamWriter(@"D:\Keywords.txt", true) 

將使用具有第二參數控制被改寫,overload of the StreamWriter constructor /添加行爲。

備選地,更可讀地,使用File.AppendText

File.AppendText(@"D:\Keywords.txt") 
相關問題