【问题标题】:Download UTF-8 web page into String将 UTF-8 网页下载为字符串
【发布时间】:2011-08-08 13:48:51
【问题描述】:

这是一个新手问题。

我阅读了the following question 以下载内容以 UTF-8 编码的网页。然后将页面转换为字节数组,而我正在使用字符串从页面中读取内容。

我需要将 UTF-8 转换为 Latin1/ANSI,因为这似乎是 RichText 和 MessageBox 使用的(我得到了有趣的字符)。

有没有更直接的方法来下载 UTF-8 页面并将其转换为 ANSI/Latin1?

谢谢。


编辑:调用 MessageBox 时,重音字符未按预期显示:

Content = CStr(e.Result)

'Théâtre, Métro MessageBox.Show(内容)

【问题讨论】:

    标签: vb.net string utf-8


    【解决方案1】:

    String 在 .NET 中一直使用 unicode,因此您不必将其转换为 to 的东西。重要的是,当您下载页面时,您需要确保标记您从 UTF-8 源加载数据。

    MSDN 有一个关于将 UTF-8 编码数据加载到字符串中的示例:

    Private Function ReadAuthor(binary_file As Stream) As String
         Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
         ' Read string from binary file with UTF8 encoding
         Dim buffer(30) As Byte
         binary_file.Read(buffer, 0, 30)
         Return encoding.GetString(buffer)
    End Function
    

    更新

    当使用WebClient.DownloadString 时,会自动转换为字符串,不需要与上述类似的代码。自动转换使用WebClient.Encoding指定的编码,所以应该通过设置WebClient对象的encoding属性为UTF-8来解决问题:

    client.Encoding = System.Text.Encoding.UTF8
    

    【讨论】:

    • 感谢您的提示。异步例程在 DownloadStringCompletedEventArgs 变量中提供网页:如何将其转换为流?
    • 查看我的更新,了解如何指定WebClient.DownloadString 使用的编码。
    猜你喜欢
    • 1970-01-01
    • 2011-08-09
    • 2013-03-02
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多