我正在尝试浏览文件夹中的所有* .txt文件,以获取内部元数据。
void SearchAndPopulate(string path, string searchText)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.txt");
Dictionary<String, dynamic> dictionary = new Dictionary<String, Object>();
int i = 0;
foreach (FileInfo file in files)
{
dictionary.Add(String.Format("name{0}", i.ToString()), i);
using (StreamReader sr = new StreamReader(file.FullName))
{
string content = sr.ReadToEnd().ToLower();
if (content.Contains(searchText.ToLower()))
{
dictionary["name"+i] = File
.ReadAllLines(file.FullName)
.Select(y => y.Split('='))
.Where(y => y.Length > 1)
.ToDictionary(y => y[0].Trim(), y => y[1]);
var temp = dictionary["name" + i];
listBox1.Text = temp["NUM_CLIENT"];
}
}
i++;
}
}
我收到“已添加具有相同键的项”的字典变量。
最佳答案
老实说,我认为您的代码中不需要任何词典。您还可以减少在每个文件中读取的次数。
void SearchAndPopulate(string path, string searchText)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.txt");
foreach (FileInfo file in files)
{
var content = File.ReadAllLines(file.FullName);
if (content.Any(line => line.ToLower().Contains(searchText.ToLower())))
{
var numClient = content.Select(y => y.Split('='))
.Where(y => y.Length > 1 && y[0].Trim() == "NUM_CLIENT")
.Select(y => y[1])
.FirstOrDefault();
if(numClient != null)
listBox1.Text = numClient;
else
// Do something here if "NUM_CLIENT" wasn't in the file.
}
}
}
关于c# - 具有相同键的项目已添加C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43451779/