rad_
rad_

Reputation: 301

Trying to search for specific value within text file

I'm trying to search for a specific value within an array of files. I'm not sure what I'm missing here, but some insight would be great.

I've tried containing all lines from each file into an array that can be read from within an if statement.

    void getAssetTag()
    {
        string path = @"\\SERVER\SHARE\FOLDER";
        DirectoryInfo d = new DirectoryInfo(path);//Grabbing Directory
        FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files

        foreach (FileInfo file in Files)
        {
            string[] asset = File.ReadAllLines(file.FullName);

            if (asset.Contains(AssetT.Text) == true) {

                string allinfo = File.ReadAllText(file.FullName);
                Results.Text = allinfo;
            }

        }
    }

The results should output the entire data from the text file contained within AssetT.Textinto Results.Text.

Upvotes: 0

Views: 80

Answers (1)

Rufus L
Rufus L

Reputation: 37070

asset is a string[], where each string is a line of text. When you do if (asset.Contains(AssetT.Text)), you're comparing an entire line to AssetT.Text.

If you want to find out if any single line contains AssetT.Text, then we need to call Contains on the line, not the array:

if (asset.Any(line => line.Contains(AssetT.Text))

Also, you're ending up reading the file twice here, once when you do ReadAllLines, and again when you do ReadAllText. Since it seems you will always read the whole file (either to determine that the file doesn't contain the text, or to get all the contents because it does contain the text), you should just do it once.

If you use File.ReadAllText in the beginning, now we have a string representation of the entire file which we can call .Contains on:

foreach (FileInfo file in new DirectoryInfo(path).GetFiles("*.txt"))
{
    string asset = File.ReadAllText(file.FullName);

    if (asset.Contains(AssetT.Text))
    {
        Results.Text = asset;

        // No use reading more files unless we're going
        // to save the contents to another variable
        break; 
    }
}

Note that we break out of the loop since it appears you're setting the contents of the file to a single field of some class, so searching for more files will just overwrite any previous results found.

This can be simplified further using System.Linq extension methods and method chaining. We can also use Directory.GetFiles (which returns a list of file paths) instead, since we don't need a full-blown FileInfo object:

Results.Text = Directory
    .GetFiles(path, "*.txt")
    .Select(File.ReadAllText)
    .FirstOrDefault(fileText => fileText.Contains(AssetT.Text)) ?? Results.Text;

Upvotes: 2

Related Questions