[英]How do I convert a byte array to a string
我有一個從 FileStream.Read 返回的字節數組,我想把它變成一個字符串。 我不能 100% 確定編碼 - 它只是我保存到磁盤的一個文件 - 我該如何進行轉換? 是否有 .NET class 可以讀取字節順序標記並可以為我找出編碼?
請參閱how-to-guess-the-encoding-of-a-file-with-no-bom-in-net 。
由於字符串是 Unicode,因此您必須在轉換時指定編碼。 文本流(甚至ReadAllText()
)內部有一個活動編碼,通常是一些合理的默認值。
嘗試這樣的事情:
buffer = Encoding.Convert( Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buffer );
newString = Encoding.UTF8.GetString( buffer, 0, len );
你對文件了解多少? 真的可以是任何編碼嗎? 如果是這樣,您需要使用啟發式方法來猜測編碼。 如果它將是 UTF-8、UTF-16 或 UTF-32 那么
new StreamReader(new MemoryStream(bytes), true)
將自動為您檢測編碼。 如果您真的不知道編碼,則文本非常討厭。 在很多情況下,您真的只是在猜測。
如果File.ReadAllText
將正確讀取文件,那么您有幾個選擇。
您可以異步調用File.ReadAllText
而不是調用BeginRead
:
delegate string AsyncMethodCaller(string fname);
static void Main(string[] args)
{
string InputFilename = "testo.txt";
AsyncMethodCaller caller = File.ReadAllText;
IAsyncResult rslt = caller.BeginInvoke(InputFilename, null, null);
// do other work ...
string fileContents = caller.EndInvoke(rslt);
}
或者,您可以從字節數組創建MemoryStream
,然后在其上使用StreamReader
。
沒有簡單的方法來獲取編碼,但如上所述使用
string str = System.Text.Encoding.Default.GetString(mybytearray);
如果您不知道編碼是什么。 如果您在歐洲,那么 ISO-8859-1 可能就是您擁有的編碼。
string str = System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(mybytearray);
System.IO.File.ReadAllText 做你想做的事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.