下载网页并保存为UTF-8文本文件

时间:2012-07-17 17:48:31

标签: c# utf-8

我按如下方式下载网页。我想将其保存为UTF-8文本。但是如何?

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
    Encoding enc = Encoding.GetEncoding(resp.CharacterSet);
    Encoding utf8 = Encoding.UTF8;
    using (StreamWriter w = new StreamWriter(new FileStream(pathname, FileMode.Create), utf8))
    {
        using (StreamReader r = new StreamReader(resp.GetResponseStream()))
        {
            // This works, but it's bad because you read the whole response into memory:
            string s = r.ReadToEnd();
            w.Write(s);

            // This doesn't work :(
            char[] buffer = new char[1024];
            int n;
            while (!r.EndOfStream)
            {
                n = r.ReadBlock(buffer, 0, 1024);
                w.Write(utf8.GetChars(Encoding.Convert(enc, utf8, enc.GetBytes(buffer))));
            }

            // This means that r.ReadToEnd() is doing the transcoding to UTF-8 differently.
            // But how?!
        }
    }
    return resp.StatusCode;
}

请勿阅读本段。正是在这里发出关于太多代码消失的警告信息。

1 个答案:

答案 0 :(得分:7)

您可以简单地使用WebClient类。它支持编码和更容易使用:

WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.DownloadFile(url, "file.txt");