要阅读我尝试了这段代码:
在 Form1 的顶部,我做了:
Dictionary<string, List<string>> LocalyKeyWords = new Dictionary<string, List<string>>();
在构造函数中我做了:
keywords = @"d:\Keywords.txt";
if (File.Exists(keywords))
{
LoadKeys(LocalyKeyWords, keywords);
}
函数加载键:
private void LoadKeys(Dictionary<string,List<string>> disctionary, string FileName)
{
var lines = File.ReadAllLines(keywords).Select(l => l.Split(','));
var dict = new Dictionary<string, List<string>>();
foreach(var splits in lines)
{
var key = splits.First();
var value = splits.Skip(1).ToList();
try {dict.Add(key, value);
}
catch(Exception ex)
{ } }
}
没有例外,但在调用函数后的构造函数中,LocalyKeyWords 为空。
这就是我今天将键和值写入文件的方式:
private void button6_Click(object sender, EventArgs e)
{
using (var w = new StreamWriter(keywords))
{
crawlLocaly1 = new CrawlLocaly();
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = crawlLocaly1.ShowDialog(this);
if (dr == DialogResult.OK)
{
if (LocalyKeyWords.ContainsKey(mainUrl))
{
LocalyKeyWords[mainUrl].Clear();
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));
}
}
}
}
也许现在您将能够解决在构造函数中加载键和值的问题,还可以解决每次在 button6 单击事件中更改键或值时如何编写的问题。