如何在不重新创建的情况下每次都写入文本文件(新建)?

时间:2012-10-10 16:20:43

标签: c# file-io

我有这个按钮点击事件:

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));
             }
         }
     }  
 }

文本文件的读取效果很好(现在进行测试并且工作正常)。 问题是,每次我点击按钮,它也会创建一个新的文本文件,我想要的是当我点击按钮时,文本文件将准备好向他添加新文本,而不是每次创建新文本之一。

我该如何解决?

1 个答案:

答案 0 :(得分:5)

听起来你只想改变这个:

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

对此:

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

这将使用overload of the StreamWriter constructor,它具有控制覆盖/追加行为的第二个参数。

或者,更可读的是,使用File.AppendText

File.AppendText(@"D:\Keywords.txt")