[英]Read the byte format of txt file in c#
假設我有一個C#控制台應用程序,並且想將文本文件的字節格式打印為字符串。 我試過了:
string bytesFromFile = System.IO.File.ReadAllBytes(@"My file here");
System.Console.Writeline(bytesFromFile);
System.Console.ReadKey();
但是它VS卻給了我一個錯誤,並說:錯誤:無法將類型'byte []'隱式轉換為'string'。 所以我嘗試了這個:
Array bytesFromFile = System.IO.File.ReadAllBytes(@"My file here");
System.Console.Writeline(bytesFromFile);
System.Console.ReadKey();
這次,它沒有給我任何錯誤,但是當我運行它時,控制台行顯示:System.Byte []
為什么是這樣? 有人可以幫我嗎?
使用UTF8編碼將字節轉換為字符串。
var bytesFromFile = System.IO.File.ReadAllBytes(@"My file here");
Console.WriteLine(Encoding.UTF8.GetString(bytesFromFile));
Console.ReadKey();
像這樣使用:
var bytesFromFile = System.IO.File.ReadAllBytes(@"My file here");
string result = System.Text.Encoding.UTF8.GetString(bytesFromFile);
System.Console.Writeline(result);
System.Console.ReadKey();
如果您不使用UTF-8,請使用Default,如下所示: Encoding.Default.GetString(bytesFromFile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.