如何使用c#保存网页?

时间:2010-08-09 12:01:54

标签: c# asp.net web

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

任何帮助?

2 个答案:

答案 0 :(得分:2)

创建一个文件选择器,如此blog所述。

然后是web client

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

答案 1 :(得分:1)

这是另一种方式:


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
}

我希望这就是你要求的。