0

There are multiple files in a folder that the code should read one by one. I have to extract some key value from the file to perform some business logic.

the file look like this,

x-sender: 
x-receiver: 
Received: 
X-AuditID:
Received: 
Received: 
From: 
To: 
Subject: 
Thread-Topic: 
Thread-Index: 
Date: 
Message-ID: 
Accept-Language: 
Content-Language: 
X-MS-Has-Attach:

There are multiple keys that can increase and decrease as per file. The order of the key could also be changed. Every key has some value.

Code:

 private void BtnStart_Click(object sender, EventArgs e)
        {
            // searches current directory

                foreach (string file in Directory.EnumerateFiles(NetWorkPath, "*.eml"))
                {

                    var dic = File.ReadAllLines(file)
                                .Select(l => l.Split(new[] { ':' }))
                                .ToDictionary(s => s[0].Trim(), s => s[1].Trim());
                    string myUser = dic["From"];

            }
        }

I was trying to read the file and convert that into dictionary , So that i can access by using Keys. But it is giving me an error "An item with the same key has already been added.".

Any help??

4

4 回答 4

3

而不是ToDictionary,您可以使用ToLookup

......same code....
.Where(s => s.Length>1)
.ToLookup(s => s[0].Trim(), s => s[1].Trim());

然后你可以检查为

string myUser = dic["From"].FirstOrDefault();
于 2013-05-30T09:27:04.823 回答
2

那是因为Receieved它在那里多次并且Dictionary不允许重复条目作为它的键值。

您可以使用Tuple<string, string>, 这将允许重复。

如果您不想返回它,您可以使用匿名类型:

foreach (string file in Directory.EnumerateFiles(NetWorkPath, "*.eml"))
{

    var items = myList
        .Select(l => l.Split(new [] {':' }, StringSplitOptions.RemoveEmptyEntries))
        .Where(l => l != null && l.Count() == 2)
        .Select(l => new
        {
            Key = l[0],
            Value = l[1],
        })
        .ToList();

    string myUser = items.First(i => i.Key == "From").Value;
}
于 2013-05-30T09:19:08.860 回答
0

您有 2 个具有相同名称的元素 - 已收到:

于 2013-05-30T09:20:01.990 回答
0

这意味着您已经在字典中添加了两次相同的键,对于您的文件内容,它已被接收:

于 2013-05-30T09:21:01.527 回答