简体   繁体   中英

how to save the webpage using c#?

How to save the webpage using c#? I need to open a dialog asking for the path to save the file.

Any help?

Create a file chooser like explained on this blog .

And then a web client

  WebClient Client = new WebClient ();
  Client.DownloadFile("pagename", " saveasname");

Here's another way:


private string DownlodHTMLPage(Uri url)
        {
            WebResponse response = null;
            Stream stream = null;
            StreamReader sr = null;

            try
            {
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
                //sometimes it doesn't work if user agent is not set
                hwr.UserAgent = "Opera/9.80 (Windows NT 5.1; U; pl) Presto/2.2.15 Version/10.10";
                response = hwr.GetResponse();
                stream = response.GetResponseStream();

                //check if content type of page is text/xxx. you can add statement for XHTML files
                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    return null;
                }

                string buffer = "", line;
                //get the stream reader
                sr = new StreamReader(stream);

                //download HTML to buffer
                while ((line = sr.ReadLine()) != null)
                {
                    buffer += line + "\r\n"; //line with new line markers
                }

                return buffer;
            }
            catch (WebException e)
            {
                System.Console.WriteLine("Can't download from " + url + " 'casue " + e);
                return null;
            }
            catch (IOException e)
            {
                System.Console.WriteLine("Can't download from " + url + " 'cause " + e);
                return null;
            }
            finally
            {
                if (sr != null)
                    sr.Close();
                if (stream != null)
                    stream.Close();
                if (response != null)
                    response.Close();
            }
        }

Edit

To answer the question in comment of Ranjana. Method above just download a web page and returns it as a string. You save it later using eg StreamWriter:


StreamWriter writer = new StreamWriter(PATH_TO_FILE, false, Encoding.UTF8);
writer.Write(DownlodHTMLPage(uri));

Path to file you can get using SaveFileDialog, eg:


SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
    string file = dialog.FileName;
    //rest of the code comes here
}

I hope that this is what you were asking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM