Home > front end >  Search for string from list into text file c# console
Search for string from list into text file c# console

Time:03-25

I need to check if my mac address is exist inside a file that contain many mac address ?

        public static string ismac;
        public static bool resultrr;
        string path = Path.GetTempPath() "555.txt";
        WebClient clienst = new WebClient();
        clienst.DownloadFile(@"http://localhost/test/mac.txt",path);
        string[] ssv = File.ReadAllLines(path);
        foreach (string items in ssv)
        {
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                ismac= nic.GetPhysicalAddress().ToString();
                if (items.Contains(ismac) == false)
                {
                    resultrr = false;
                }
                else
                {
                    resultrr = true;
                }
            }
            Console.ReadKey();
        }

i feel confused, any help to get the working interface mac and compaire it with the text file ?

CodePudding user response:

My Visual Studio is still updating. I am writing this on notepad, so please excuse typos.

So, with minimum changes to your existing code, this should work -

public static string ismac;
public static bool resultrr;
string path = Path.GetTempPath() "555.txt";
WebClient clienst = new WebClient();
clienst.DownloadFile(@"http://localhost/test/mac.txt",path);
string[] ssv = File.ReadAllLines(path);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
    ismac = nic.GetPhysicalAddress().ToString();
    resultrr = ssv.Any(x => x.Contains(ismac));
    if(resultrr) break;
}
Console.ReadKey();

This should set resultrr should have value true if your mac is there in the list.

You should re consider few more things in your code like replacing WebClient with HttpClient, using using statement around your client.

CodePudding user response:

In your code, if the MAC address is matched it will set resultrr to true and then immediately set it to false again on the next iteration.

If you want it to return true on a single match, you could split this into its own method and just return true on the first match.

public bool MACFound()
{
    …
    string[] ssv = File.ReadAllLines(path);
    foreach (string items in ssv)
    {
        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            ismac= nic.GetPhysicalAddress().ToString();
            if (items.Contains(ismac) == true)
            {
                return true;
            }
        }
    }
    return false;
}

If not you at least need to set returnrr to false before the loops begin and delete the assignment to false within the loop. No reason not to break out of the loop early unless you’re doing something else like counting the number of occurrences, though.

  • Related