0

在单击按钮事件中,我做了:

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

当它第一次文本文件不存在时它可以,但是当文件存在并且里面已经有 url 和键时,我得到了同样的错误:LocalyKeyWords[values[0]].Clear();

错误是:字典中不存在给定的键。我看到值在索引 [0] 中包含两个索引,在 url 和索引 [1] 中,键和 LocalyKeyWords 也包含一个索引,即值。

那么我该如何解决这个问题呢?当我在构造函数中运行程序时,即使我没有点击按钮,我如何加载文本文件?

在构造函数中运行程序时以及单击按钮时如何加载文本文件?

谢谢。

4

1 回答 1

1

如果您不想丢失所有更改,则必须先读取文件并将其值存储在字典中。如果你想覆盖现有的 url 键,那么你应该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));
            }
        }
    }
}
于 2012-10-10T06:02:57.357 回答