3

I have a url and on entering this url, i am getting a html page. What i want is to save that html page on the server from that url. Here is the code-

 protected void one_Click(object sender, EventArgs e)
    {
        string s = textbox.Text;
        var code = s.Split(new[] { "mailerhtml" }, StringSplitOptions.None)[1];
        string product = code.Replace(@"/", string.Empty);
}

In the above code i am entering a url and on one_Click of a button(one) i am saving the textbox text in a string 's'. Additionally, variable 'code' is used to get the name by which i will we saving the html page. for eg- if code is'abc', i will be saving it as code.html Now, i have a folder named 'HTMLPages' on my server and i want to save the html pages in this folder. How can i achieve this?

manu sharma
  • 140
  • 11
  • but the variable 'code' is not having any extension – manu sharma Nov 03 '18 at 12:15
  • instead of opening that url and saving it using windows save as option on the system, i want to save that url as html page – manu sharma Nov 03 '18 at 12:19
  • Possible duplicate of [How can I download HTML source in C#](https://stackoverflow.com/questions/599275/how-can-i-download-html-source-in-c-sharp) – SᴇM Nov 03 '18 at 12:20
  • Possible duplicate of [How to download a file from a URL in C#?](https://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c) – Charlie Salts Nov 03 '18 at 13:52

1 Answers1

2

You have to use web client for that purpose it will download it and you can write a file where you want.

 WebClient myClient = new WebClient();
        string myPageHTML = null;
        byte[] requestHTML; 
        // Gets the url of the page
        string currentPageUrl = Request.Url.ToString();

        UTF8Encoding utf8 = new UTF8Encoding();

        // by setting currentPageUrl to url it will fetch the source (html) 
        // of the url and put it in the myPageHTML variable. 

       // currentPageUrl = "url"; 

        requestHTML = myClient.DownloadData(currentPageUrl);

        myPageHTML = utf8.GetString(requestHTML); 

        System.IO.File.WriteAllText(@"C:\yoursite.html", myPageHTML);
Hamza Haider
  • 730
  • 6
  • 20