簡體   English   中英

從列表中搜索字符串到文本文件 c# 控制台

[英]Search for string from list into text file c# console

我需要檢查我的 mac 地址是否存在於包含許多 mac 地址的文件中?

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

我感到很困惑,對於獲取工作界面 mac 並將其與文本文件進行比較有什么幫助嗎?

我的 Visual Studio 仍在更新。 我是在記事本上寫的,所以請原諒打字錯誤。

因此,只需對現有代碼進行最少的更改,這應該可行 -

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

如果您的 mac 在列表中,這應該設置resultrr應該具有值 true。

您應該重新考慮代碼中的更多內容,例如將WebClient替換為HttpClient ,在客戶端周圍使用using語句。

在您的代碼中,如果 MAC 地址匹配,它將 resultrr 設置為 true,然后在下一次迭代中立即再次將其設置為 false。

如果您希望它在單個匹配項上返回 true,您可以將其拆分為它自己的方法,並在第一個匹配項上return true

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

如果不是,您至少需要在循環開始之前將 returnrr 設置為 false,並在循環中刪除對 false 的賦值。 不過,沒有理由不盡早跳出循環,除非您正在做其他事情,例如計算出現的次數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM