在单击按钮事件中,我这样做了:
if (File.Exists(@"d:\Keywords.txt"))
{
entries = File.ReadAllLines(@"d:\Keywords.txt");
foreach (string entry in entries)
{
string[] values = entry.Split(',');
if (LocalyKeyWords.Count == 0)
{
LocalyKeyWords[values[0]] = new List<string>();
}
else
{
LocalyKeyWords[values[0]].Clear();
}
for (int i = 1; i < values.Length; i++)
LocalyKeyWords[values[0]].Add(values[i]);
}
}我添加/更改的部分是:
if (LocalyKeyWords.Count == 0)
{
LocalyKeyWords[values[0]] = new List<string>();
}
else
{
LocalyKeyWords[values[0]].Clear();
}并且当它第一次不存在文本文件时,它是ok的,但是当文件存在并且已经有url和key时,im得到相同的错误: LocalyKeyWords[values].Clear();
错误是:给定的键在字典中不存在。我看到值包含两个索引,在索引中,url和索引1,键和LocalyKeyWords包含一个索引,这就是值。
那么我该如何解决这个问题呢?当我在构造函数中运行程序时,我如何加载文本文件,即使我没有点击按钮?
如何使在构造函数中运行程序时加载文本文件一次和单击按钮时加载一次文本文件?
谢谢。
发布于 2012-10-10 14:02:57
如果不想丢失所有更改,则必须先读取文件并将其值存储在字典中。如果你想覆盖urls的现有键,那么你应该每次都清除你的List。例如:
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));
}
}
}
}https://stackoverflow.com/questions/12812644
复制相似问题