我有这个按钮点击事件:
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));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
阅读文本文件工作得很好(这是为了现在的测试和它的工作好).问题是,每次我点击按钮,它也会创建一个新的文本文件,我想要的是当我点击按钮时,文本文件将准备好向他添加新文本,而不是每次创建新文本一.
我怎么解决这个问题?
听起来你只是想改变这个:
new StreamWriter(@"D:\Keywords.txt")
Run Code Online (Sandbox Code Playgroud)
对此:
new StreamWriter(@"D:\Keywords.txt", true)
Run Code Online (Sandbox Code Playgroud)
这将使用构造函数的重载,该StreamWriter构造函数具有控制覆盖/附加行为的第二个参数.
或者,更可读,使用File.AppendText:
File.AppendText(@"D:\Keywords.txt")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
278 次 |
| 最近记录: |