C# 在c中读取txt文件的字节格式#

C# 在c中读取txt文件的字节格式#,c#,byte,C#,Byte,假设我有一个C#控制台应用程序,我想将文本文件的字节格式打印为字符串。我试过: string bytesFromFile = System.IO.File.ReadAllBytes(@"My file here"); System.Console.Writeline(bytesFromFile); System.Console.ReadKey(); 但它只给了我和error,并说:error:无法隐式地将类型“byte[]”转换为“string”。于是我尝试了这个: Array bytesFr

假设我有一个C#控制台应用程序,我想将文本文件的字节格式打印为字符串。我试过:

string bytesFromFile = System.IO.File.ReadAllBytes(@"My file here");
System.Console.Writeline(bytesFromFile);
System.Console.ReadKey();
但它只给了我和error,并说:error:无法隐式地将类型“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();

如果您没有使用/sure about UTF-8,请使用如下默认值:
Encoding.Default.GetString(bytesFromFile)

您实际上想做什么?文件的内容是什么,您希望打印出什么?将第一个代码ReadAllBytes更改为ReadAllText。您如何知道OP的文件使用UTF-8编码?如果不确定,则使用
encoding.Default.GetString(array)
,例如,如果编码为UTF-16,也可能会失败。这就是猜测的问题。你怎么知道OP的文件使用UTF-8编码?