how can i convert string to System.Net,IPAddress in C#/.net 3.5
i tried this but i got this error "Cannot convert type 'string' to '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();
}
}
}
ReadAllLines("proxy. txt"). Select(s => IPAddress. Parse(s))) { // ... }
The IPAddress class contains the address of a computer on an IP network. Example. The following example creates an IPAddress instance and then uses that instance to perform a DNS query for host information: IPAddress myIP = IPAddress.
An IP address is a string of numbers separated by periods. IP addresses are expressed as a set of four numbers — an example address might be 192.158. 1.38. Each number in the set can range from 0 to 255.
Use the static IPAddress.Parse
method to parse a string
into 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 TryParse
to avoid any exceptions being thrown.
The IPAddress.Parse
method accepts a string.
foreach (string line in File.ReadAllLines("proxy.txt"))
{
IPAddress ip = IPAddress.Parse(line);
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With