开发者

how to save the webpage using c#?

Ho开发者_如何学运维w 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 e.g StreamWriter:


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

Path to file you can get using SaveFileDialog, e.g.:


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜