Dec 27
Reading the contents of a web page is easy in C# with the System.Net.WebClient class:
using System.Net; using System.Windows.Forms; string url = "http://www.devtopics.com"; string result = null; try { WebClient client = new WebClient(); result = client.DownloadString( url ); } catch (Exception ex) { // handle error MessageBox.Show( ex.Message ); }
The web page is read into the ‘result’ string. Note the URL you pass to the DownloadString method must have the http:// prefix, otherwise it will throw a WebException.
A more complicated but also more flexible solution is to use the System.Net.HttpWebRequest class, which enables you to interact directly with servers using HTTP:
using System.Net; using System.IO; using System.Windows.Forms; string result = null; string url = "http://www.devtopics.com"; WebResponse response = null; StreamReader reader = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create( url ); request.Method = "GET"; response = request.GetResponse(); reader = new StreamReader( response.GetResponseStream(), Encoding.UTF8 ); result = reader.ReadToEnd(); } catch (Exception ex) { // handle error MessageBox.Show( ex.Message ); } finally { if (reader != null) reader.Close(); if (response != null) response.Close(); }
You can also add headers in both WebClient and HttpWebRequest. Take a look at http://msdn2.microsoft.com/en-us/library/system.net.webclient.aspx and http://msdn2.microsoft.com/en-us/library/system.net.httpwebrequest.headers(VS.85).aspx
Sorry 🙁
Please–remember that if an object supports IDisposable you should *always* invoke Dispose. Since that’s not convenient, instead wrap the code in using block like this:
Uri target = new Uri(LocalTestPagesFullURL + “/” + relative_path);
LH.info(“Running test for “, target);
using (System.Net.WebClient client = new System.Net.WebClient())
{
byte[] data = client.DownloadData(target);
} //using
Don’t think you need to do this? Keep writing code, you’ll find out for yourself at 2am…
I know this is a somewhat old post, but nevertheless…
I always strongly suggest avoiding WebClient for everything but one-time-only scripting usage. WebClient is unfortunately not properly encoding-aware, and it trashes the relevant HTTP headers so you cannot manually determine the correct encoding should it fail. Essentially, when WebClient doesn’t find an encoding specified as a charset, it uses your local system’s default codepage, which is generally not what you want.
To avoid potential data-corruption issues, I’d avoid it.
hello
Can I place a text file (xyz.txt) in my own url
and then whereever I go I can download it into string[] using c# ?
can u suggest the code ?
@denny: The code above will do it for you. Just replace the url string literal, such as:
string url = “http://www.mywebsite.com/xyz.txt”;
Thanks a bunch man you helped me a lot with that simple example i appreciate it !
israeli guy
Thanks man , that should come in handy at some point 🙂
ha ha Excellent