[英]How do I read Little Endian encoded files in C#?
我有一個來自 HttpWebResponse 的 stream,當我使用下面的代碼讀取並基本上在我的本地計算機上重新創建文件時。
string sx = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream resStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(resStream, Encoding.Default); // I have also tried using Encoding.UTF8/7/ASCII etc.
sx = reader.ReadToEnd();
// sourceItem.Name would have the file name along with the extension.
using (StreamWriter sw = System.IO.File.AppendText(sourceItem.Name))
{
sw.Write(sx);
}
}
response.Close();
}
但是當我在本地機器上打開文件時,我得到了所有奇怪的垃圾符號。
圖片:
我相信這是文件編碼的問題。 我在 git bash 上使用file *
來檢查編碼,結果是Little Endian 。 小端截圖
但不幸的是,我在System.Text.Encoding
中看不到Little Endian 。 我該如何解決我的問題?
謝謝您的幫助。
我該如何解決我的問題?
您確定您的 http 端點返回文本嗎? 我的猜測是,這將返回一些二進制文件,而不是如您所期望的文本文件。 如果你想直接將二進制響應寫入文件,你可以這樣做,如果我沒記錯的話:
using (Stream input = response.GetResponseStream())
using (Stream output = File.Open(sourceItem.Name, FileMode.Append))
{
input.CopyTo(output);
}
我想知道你為什么要附加到文件中。 如果你想“基本上在我的本地機器上重新創建文件”,我希望將完整的響應寫成一個文件,會更好。 喜歡:
using (Stream input = response.GetResponseStream())
using (Stream output = File.OpenWrite(sourceItem.Name))
{
input.CopyTo(output);
}
如果這不是問題所在,我會通過以下步驟與 go 聯系:
sx = reader.ReadToEnd();
之后設置一個斷點。 並檢查sx
以查看生成的字符串是否正確。 如果不是,則需要嘗試不同的編碼。 也許檢查 Postman 中的標頭或瀏覽器的調試工具,看看它們是否包含有關編碼的提示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.