TimmRH TimmRH - 2 months ago 11
C# Question

C# search all files in a directory that contain a string, then return that string

Using user inpit into a textbox, I want to search for which file in the directory contains that text. I would then like to parse out the information

but I can't seem to find the string or at least return the information. Any help would be greatly appreciated.

My current code:

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);
}
}
}
}
}
}
}
}

Answer

You seem quite lost. Why are you using a dynamic when a string is all that you need? Your code has too many unnecessary variables and convertions. Here's a much simpler way to do it. I don't know what you want the label to have if there are many matching lines, here I'm only placing the first one there:

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;
    }
}