Asım Gündüz
Asım Gündüz

Reputation: 1297

Getting a String From a website

Hi I'm trying to write a program where I could get my public ip address from http://ifconfig.me/ip

but my code fails.. the program compiles but when I press the button to get the ip and display it on a txtbox the program is frozen I have tried the following code

using system.xml;
XmlDocument document = new XmlDocument();
document.Load("http://ifconfig.me/ip");
string allText = document.InnerText;

and my other code is

using system.net
WebClient abc = new WebClient();
txtMyIp.Text = abc.DownloadString("http://www.ifconfig.me/ip");

can any one tell me why the program freezes when I press the button? or suggest me any other way/method?

btw I am using visual studio 2012

Upvotes: 1

Views: 179

Answers (5)

Oleksii Aza
Oleksii Aza

Reputation: 5398

  1. Your UI freezes because you downloading string from website in UI thread, which means that your UI thread can only wait unitl your abc.DownloadString("http://www.ifconfig.me/ip"); executes. Istead of that I would recommend you to use async/await and HttpClient from System.Net.Http. Your code would look like this:

    private async void button1_Click(object sender, EventArgs e)
    {
        using (var abc = new HttpClient())
        {
           var uri = new Uri(@"http://www.ifconfig.me/ip");
           txtMyIp.Text = await abc.GetStringAsync(uri);
        }
    }
    
  2. Note that you can do the same with WebClient by calling abc.DownloadStringTaskAsync(uri), but HttpClient should be quicker because it doesn't contain the stuff related with web browser simulation like WebClient.
  3. Also note that with both APIs you should dispose your client by wrapping it in using statement because it has to free some resources, for example close the stream opened for incoming data.
  4. If you are using .NET Framework of version less that 4.5 and want to use WebClient - try this code snippet, it shouldn't freeze your UI:

    private void button1_Click(object sender, EventArgs e)
    {
        using (var abc = new WebClient())
        {
            var uri = new Uri(@"http://www.ifconfig.me/ip");
            abc.DownloadStringCompleted += (o, args) => txtMyIp.Text = args.Result;
            abc.DownloadStringAsync(uri);
        }
    }
    
  5. I noticed that sometimes http://www.ifconfig.me/ip returns permanent redirect to http://ifconfig.me/ip, thus I think you should use address without www.

Upvotes: 1

Pierre
Pierre

Reputation: 417

You should try downloading the string asynchronously:

Uri uri = new Uri("http://ifconfig.me/ip");
XmlDocument xmlDocument = await XmlDocument.LoadFromUriAsync(uri);
string result = xmlDocument.ToString();

Upvotes: 0

gustavodidomenico
gustavodidomenico

Reputation: 4681

Tried in the LINQPad with success (remember to add the System.Net namespace):

void Main()
{
    var  client = new WebClient();
    Console.WriteLine(client.DownloadString("http://www.ifconfig.me/ip"));
}

Result:

177.156.151.233

PS: Linqpad: https://www.linqpad.net/

Upvotes: 1

DonBoitnott
DonBoitnott

Reputation: 11025

An alternative approach:

using System.IO;
using System.Net;

String url = "http://ifconfig.me/ip";
String responseFromServer = null;
try
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        using (Stream dataStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(dataStream))
                responseFromServer = reader.ReadToEnd();
        }
    }
}
catch { }

if (!String.IsNullOrEmpty(responseFromServer))
    MessageBox.Show(responseFromServer);

Upvotes: 1

Jevgeni Geurtsen
Jevgeni Geurtsen

Reputation: 3133

It is the website that causes to do it. Its just taking ages to load. You should try using another website: http://wtfismyip.com/text I've tried

string myIP = new WebClient().DownloadString("http://wtfismyip.com/text");

and it worked fine.

Upvotes: 3

Related Questions