Как сохранить веб-страницу с помощью C #? - PullRequest
0 голосов
/ 09 августа 2010

Как сохранить веб-страницу с помощью c #?Мне нужно открыть диалоговое окно с просьбой указать путь для сохранения файла.

Любая помощь?

Ответы [ 2 ]

2 голосов
/ 09 августа 2010

Создайте средство выбора файлов, как описано в этом блоге .

А затем веб-клиент

  WebClient Client = new WebClient ();
  Client.DownloadFile("pagename", " saveasname");
1 голос
/ 09 августа 2010

Вот еще один способ:


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

Редактировать

Чтобы ответить на вопрос в комментарии Ранджаны.Метод выше просто скачать веб-страницу и возвращает ее в виде строки.Вы сохраните его позже, используя, например, 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
}

Я надеюсь, что это то, что вы просили.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...