private void button6_Click(object sender, EventArgs e)
{
string[] entries = File.ReadAllLines(@"D:\Keywords.txt");
foreach (string entry in entries)
{
string[] values = entry.Split(',');
LocalyKeyWords[values[0]].Clear();
for (int i = 1; i < values.Length; i++)
LocalyKeyWords[values[0]].Add(values[i]);
}
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));
}
}
}
}
错误在线:
LocalyKeyWords[values[0]].Clear();
错误是:KeyNotFoundException: The given key was not present in the dictionary
LocalyKeyWords 是一个列表:
Dictionary<string, List<string>> LocalyKeyWords = new Dictionary<string, List<string>>();
而且文件Keywords.txt
现在不是空的:
http://www.cnet.com,changing for test
http://www.wlala.co.co,adding
然而,在阅读文件时,我遇到了异常。我在错误行上看到它LocalyKeyWords
为空 0 但值包含两个索引:
[0] http://www.cnet.com and [1] changing for test
索引 0 是 url,索引 1 是 url 键!
我尝试在此行之前添加并将那里的代码更改为:
if (LocalyKeyWords.Count == 0)
{
LocalyKeyWords[values[0]] = new List<string>();
}
else
{
LocalyKeyWords[values[0]].Clear();
}
但它没有用,也没有解决问题。我仍然在线上遇到错误。我该如何解决?
该列表是这样构建的: url,例如键:http://www.google.com ","google 文本文件格式也是这样的:
http://www.cnet.com,changing for test
http://www.wlala.co.co,adding
更改测试是http://www.cnet.com的关键 ,addin 是http://www.wlala.co.co的关键
所以我想在从文本文件中读回 url,key 时做两件事:
要将 url 及其所属键添加到 a
ListBox
所以我在构造函数中完成了它。每次用户更改 url 的键或添加新的 url 及其键时,我想在按钮单击事件中执行此操作,以便用户实时看到 ListBox 中的更改。在构造函数中,我添加了 url 和键并将其显示在 ListBox 中,如下所示: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); listBox1.Items.Add("Url: " + key_of_each_line + " --- " + "Key: " + value_of_each_key ); } sr.Close();
sr 是一个StreamReader
。它在构造函数中运行良好。构造函数中的格式相同。当用户添加新/更改键/s或url/s时,我想在按钮单击事件中实时显示它
- 修复现在在按钮单击事件中出现异常错误的读取部分。
新阅读部分代码:
if (File.Exists(@"d:\Keywords.txt"))
{
string[] entries = File.ReadAllLines(@"D:\Keywords.txt");
foreach (string entry in entries)
{
string[] values = entry.Split(',');
if (LocalyKeyWords.ContainsKey(values[0]))
LocalyKeyWords[values[0]].Clear();
else
LocalyKeyWords[values[0]] = new List<string>();
for (int i = 1; i < values.Length; i++)
LocalyKeyWords[values[0]].Add(values[i]);
}
}
还添加了检查文件是否存在以防用户删除它。但是如果文件存在,我不希望每次用户单击按钮时都会创建一个新的空文本文件。