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 是每次我单击按钮时,它也会创建一个新的文本文件,我想要的是,当我单击按钮时,文本文件将准备好向他添加新文本,而不是每次都创建一个新的一。

我该如何解决?

4

1 回答 1

5

听起来你只想改变这个:

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

对此:

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

这将使用具有第二个参数控制覆盖/附加行为的构造函数的重载。StreamWriter

或者,更易读,使用File.AppendText

File.AppendText(@"D:\Keywords.txt")
于 2012-10-10T16:22:02.410 回答