繁体   English   中英

如何使用C#保存网页?

[英]how to save the webpage using c#?

如何使用C#保存网页? 我需要打开一个对话框,询问保存文件的路径。

有什么帮助吗?

创建一个文件选择器,如本博客中所述

然后是一个网络客户端

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

这是另一种方式:


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();
            }
        }

编辑

回答评论中的问题Ranjana。 上面的方法只是下载一个网页并以字符串形式返回。 您稍后使用StreamWriter保存它:


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

您可以使用SaveFileDialog获得的文件路径,例如:


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

我希望这就是您要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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