C# 如何将字符串转换为 System.Net.IPAddress

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12037772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:10:03  来源:igfitidea点击:

how to convert string to System.Net.IPAddress

c#.netip-address

提问by user1608298

how can i convert string to System.Net,IPAddress in C#/.net 3.5

如何在 C#/.net 3.5 中将字符串转换为 System.Net,IPAddress

i tried this but i got this error "Cannot convert type 'string' to 'System.Net.IPAddress'"

我试过了,但我收到这个错误“无法将类型'字符串'转换为'System.Net.IPAddress'”

 public void Form1_Load(object sender, EventArgs e)
    {
        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in File.ReadAllLines("proxy.txt"))
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                localIP = ip.ToString();
                textBox1.Text = ip.ToString();
            }
        }

   }

回答by TrizZz

You can use IPAddress.Parse Method for example:

例如,您可以使用 IPAddress.Parse 方法:

private static void parse(string ipAddress)
  {
    try
    {
      IPAddress address = IPAddress.Parse(ipAddress);
    }

回答by Oded

Use the static IPAddress.Parsemethod to parse a stringinto an IPAddress:

使用静态IPAddress.Parse方法将 a 解析string为 an IPAddress

foreach (var ipLine in File.ReadAllLines("proxy.txt"))
{
    var ip = IPAddress.Parse(ipLine);
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
        textBox1.Text = ip.ToString();
    }
}

If the lines in the file are not always valid IP addresses, you may want to consider using TryParseto avoid any exceptions being thrown.

如果文件中的行并不总是有效的 IP 地址,您可能需要考虑使用TryParse以避免抛出任何异常。

回答by Richard

foreach (IPAddress ip in File.ReadAllLines("proxy.txt").Select(s => IPAddress.Parse(s))) {
    // ...
}

回答by Timbo

You can use IPAddress.Parseto do that.

您可以使用IPAddress.Parse来做到这一点。

回答by Steven Doggart

The IPAddress.Parsemethod accepts a string.

IPAddress.Parse方法接受一个字符串。

foreach (string line in File.ReadAllLines("proxy.txt"))
{
    IPAddress ip = IPAddress.Parse(line);
    // ...
}

回答by Jason Cidras

One thing you can do is this... In the foreach loop, you need an instance that matches your collection. What I mean is that if you have, for instance, you have a List of strings, like this:

您可以做的一件事是...在 foreach 循环中,您需要一个与您的集合相匹配的实例。我的意思是,例如,如果您有一个字符串列表,如下所示:

    List<string> lMyList    

A programmer cannot iterate through this list with an instance of an int or a double...

程序员无法使用 int 或 double 的实例遍历此列表...

    foreach (int lIterator in lMyList) 
    { // code 
    }

This simply will not work and it will throw a syntax error about an "int" isn't a type of "string".

这根本行不通,它会抛出一个关于“int”不是“字符串”类型的语法错误。

To solve that, you will need to iterate through your list like this

要解决这个问题,您需要像这样遍历您的列表

    foreach (string lIterator in lMyList)
    { // code
    }

Now, to your question. An IPAddress is it's own class and type. One cannot simply make it a type of string. However, there are ways to get around this. Explicitly convert a string to an IP address. But, you will need to iterate over your list first.

现在,回答你的问题。IPAddress 是它自己的类和类型。不能简单地使它成为一种字符串。但是,有一些方法可以解决这个问题。将字符串显式转换为 IP 地址。但是,您需要先遍历您的列表。

    foreach (string lLine in File.ReadAllLines("proxy.txt"))
    {
        // Code In Here
    }

This will iterate all the lines in the text file. Since it's a text file, it returns a list of strings. In order to iterate over a list of strings, a programmer needs a string local variable to iterate over it.

这将迭代文本文件中的所有行。由于它是一个文本文件,它返回一个字符串列表。为了迭代字符串列表,程序员需要一个字符串局部变量来迭代它。

Next, you will need to parse the current string to a local IP Address instance. There are a few ways of doing this, 1) You can simply Parse (System.Net.IPAddress.Parse()) the string, or you can TryParse (IPAddress.TryParse()) a string into an IPAddress.

接下来,您需要将当前字符串解析为本地 IP 地址实例。有几种方法可以做到这一点,1) 您可以简单地解析 (System.Net.IPAddress.Parse()) 字符串,或者您可以 TryParse (IPAddress.TryParse()) 将字符串转换为 IPAddress。

    Method One:
    // This will parse the current string instance to an IP Address instance
    IPAddress lIPAddress = IPAddress(lLine);

    Method Two:
    IPAddress lIPAddress; // Local instance to be referenced
    // At runtime, this will "Try to Parse" the string instance to an IP Address.
    // This member method returns a bool, which means true or false, to say,
    // "Hey, this can be parsed!". Your referenced local IP Address instance would
    // have the value of the line that was parsed.
    if (IPAddress.TryParse(lLine, out lIPAddress)) 
    {
        // Code
    }

Okay, now we got that out of the way. Lets finish this up.

好的,现在我们解决了这个问题。让我们完成这件事。

    // Iterates over the text file.
    foreach (string lLine in File.ReadAllLines("proxy.txt"))
    {
        // Create a local instance of the IPAddress class. 
        IPAddress lIPAddress;
        // Try to Parse the current string to the IPAddress instance.
        if (IPAddress.TryParse(lLine, out lIPAddress))
        {
            // This means that the current line was parsed.
            // Test to see if the Address Family is "InterNetwork"
            if (string.Equals("InterNetwork", lIPAddress.AddressFamily.ToString()))
            {
                TextBox1.Text = lIPAddress.ToString();
            }
        }
    }

I hope this helps!

我希望这有帮助!