在文本框中使用用户输入,我想搜索目录中哪个文件包含该文本。然后我想解析信息
但我似乎无法找到字符串或至少返回信息。任何帮助将不胜感激。
我目前的代码:
private void btnSearchSerial_Click(object sender, EventArgs e)
{
dynamic dirScanner = @"\\mypath\";
string strSerial;
string strSID;
string strInputLine;
string strOutput;
strSerial = Convert.ToString(txtSerialSearch);
strSID = Convert.ToString(txtSID);
if (txtSerialSearch.Text != "" && txtSID.Text != "")
{
try
{
string[] allFiles = Directory.GetFiles(dirScanner);
foreach (string file in allFiles)
{
if (file.EndsWith(".txt"))
{
using (StreamReader sr = new StreamReader(file))
{
while (sr.Peek() >= 0)
{
strInputLine = sr.ReadLine();
if (strInputLine.Contains(strSerial))
{
strOutput = Convert.ToString(strInputLine);
lblOutput.Text = Convert.ToString(strOutput);
}
}
}
}
}
}
}
}
答案 0 :(得分:7)
dynamic
时,为什么使用string
?您的代码有太多不必要的变量和转换。这是一种更简单的方法。如果有很多匹配的行,我不知道你想要的标签,这里我只放置第一个:
string dirScanner = @"\\mypath\";
if (string.IsNullOrWhiteSpace(txtSerialSearch.Text) || string.IsNullOrWhiteSpace(txtSID.Text))
return;
string[] allFiles = Directory.GetFiles(dirScanner, "*.txt");
foreach (string file in allFiles)
{
string[] lines = File.ReadAllLines(file);
string firstOccurrence = lines.FirstOrDefault(l => l.Contains(txtSerialSearch.Text));
if (firstOccurrence != null)
{
lblOutput.Text = firstOccurrence;
break;
}
}
答案 1 :(得分:2)
我使用正则表达式实现了相同的功能。您需要使用名称空间using System.Text.RegularExpressions;
string strSerial = @"Microsoft";
Regex match = new Regex(strSerial);
string matchinglines = string.Empty;
List<string> filenames = new List<string>(Directory.GetFiles(textBox1.Text));
foreach(string filename in filenames)
{
//StreamReader strFile = new StreamReader(filename);
string fileContent = File.ReadAllText(filename);
if(match.IsMatch(fileContent))
{
label1.Text = Regex.Match(fileContent, strSerial).ToString();
break;
}
}