Get Remote HTML Code as String

Knowledge Base Entry: #95
^Top
<< Back
Mobile-Menu










Get Remote HTML Code as String
Category: C-Sharp/Snippets
Author: Bugfish
Created at: 2020-11-22 17:58:28
Modified at: 2025-09-19 17:26:50
Directs Hits: 774

Here is an example function to get the full html output code of an URL provided to the function into a string.
You can get the data by using a string variable which gets the output:

string variable = gethtmlcontent("https://thisisapage");

            public string gethtmlcontent(String URL)
            {
                    HttpWebRequest request;
                    HttpWebResponse response;
                        try
                        {   request = (HttpWebRequest)WebRequest.Create(URL);
                            response = (HttpWebResponse)request.GetResponse();
                        }  catch (WebException) { this.searchcode = false;  return null; }
                           catch (Exception) { this.searchcode = false; return null; }

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Stream receiveStream = response.GetResponseStream();
                        StreamReader readStream;
                        if (String.IsNullOrWhiteSpace(response.CharacterSet)){
                                readStream = new StreamReader(receiveStream);}
                        else {readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));}
                        string data = readStream.ReadToEnd();
                        response.Close();
                        readStream.Close();
                        return data;
                    }
                    
                    this.contextcode = false;
                    response.Close();
                    return null;
            }

Caution: I do not guarantee the reliability of the information given here, the code described on this page is executed at your own risk and in the event of damage or other unforeseeable consequences I am in no way responsible or liable.
This Website is using Session Cookies for Site Functionality.