how to convert string to System.Net.IPAddress
46,096
Solution 1
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.
Solution 2
The IPAddress.Parse
method accepts a string.
foreach (string line in File.ReadAllLines("proxy.txt"))
{
IPAddress ip = IPAddress.Parse(line);
// ...
}
Solution 3
foreach (IPAddress ip in File.ReadAllLines("proxy.txt").Select(s => IPAddress.Parse(s))) {
// ...
}
Solution 4
You can use IPAddress.Parse Method for example:
private static void parse(string ipAddress)
{
try
{
IPAddress address = IPAddress.Parse(ipAddress);
}
Solution 5
You can use IPAddress.Parse to do that.
Author by
user1608298
Updated on June 25, 2020Comments
-
user1608298 almost 4 years
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(); } } }