如何使新密钥(关键字)替换旧密钥(关键字)?

时间:2012-10-10 05:41:51

标签: c#

在点击按钮事件中我做了:

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和index [1]键和LocalyKeyWords als包含一个索引,它是值。

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

如果在构造函数中运行程序时加载文本文件,并在单击按钮时加载一次,该怎么做?

感谢。

1 个答案:

答案 0 :(得分:1)

如果您不想丢失所有更改,则必须首先读取文件并将其值存储在字典中。如果您想覆盖网址的现有密钥,那么您应该每次都清除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));
            }
        }
    }
}