【问题标题】:Can't convert UTF8 to default encoding无法将 UTF8 转换为默认编码
【发布时间】:2016-07-13 11:14:06
【问题描述】:

我正在尝试通过 RESTful Web 服务下载文件,然后将文件保存在计算机上。

我正在使用 PDF 文件来测试代码。我发现数据是 UTF-8 编码的,所以我尝试将其编码回默认值,因为我通过在本地读取 pdf 文件并再次将其写回发现它是这样工作的。

这是我的代码:

IConsumerRequest getDocumentRequest = class.consumerSession
    .Request()
    .ForMethod("GET")
    .ForUri(new Uri(class.apiEndpoint + "/1/documents/" + id))
    .SignWithToken(class.accessToken);

string test = System.IO.File.ReadAllText("C:\\test.pdf", Encoding.Default);

byte[] bytes = Encoding.UTF8.GetBytes(getDocumentRequest.ToString());
string data = Encoding.Default.GetString(bytes);

MessageBox.Show(test.Substring(0, 120) + "\n\n" + data.Substring(0, 120));

SaveFileDialog saveFileDialog = new SaveFileDialog();

saveFileDialog.FileName = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();

if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
    System.IO.File.WriteAllBytes(saveFileDialog.FileName, bytes);
}

比较字符串显示以下内容(第二行): Local String vs String from Webservice

我已经尝试了几种方法来转换字符串,没有任何区别。

【问题讨论】:

    标签: c# encoding utf-8


    【解决方案1】:

    您可以使用Encoding.Convert 方法。

    byte[] converted = Encoding.Convert(Encoding.UTF8, Encoding.Default, bytes);
    

    【讨论】:

    • 谢谢,但是使用这个效果完全一样。
    • @TimoRzipa - 如果使用将编码类型作为最后一个参数的WriteAllBytes 重载会发生什么?
    • 没有重载也采用编码类型。字节没有以任何方式编码,所以问题必须在字符串的某个地方。我想也许这甚至不是我的错,而是网络服务的问题。
    • 抱歉,我的意思是 WriteAllText
    【解决方案2】:

    让它与 HttpWebResponse 一起工作:

    HttpWebResponse webResponse = getDocumentRequest.ToWebResponse();
    
    Stream stream = webResponse.GetResponseStream();
    Encoding enc = System.Text.Encoding.GetEncoding(UTF8);
    StreamReader loResponseStream = new StreamReader(webResponse.GetResponseStream(), enc);
    
    string serverResponse = loResponseStream.ReadToEnd();
    
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    
    saveFileDialog.FileName = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
    
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        System.IO.File.WriteAllText(saveFileDialog.FileName, serverResponse, Encoding.Default);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 2016-02-07
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 2023-03-21
      相关资源
      最近更新 更多