简体   繁体   English

如何将字节数组转换为字符串

[英]How do I convert a byte array to a string

I have a byte array which I got back from a FileStream.Read and I would like to turn that into a string.我有一个从 FileStream.Read 返回的字节数组,我想把它变成一个字符串。 I'm not 100% sure of the encoding - it's just a file i saved to disk - how do I do the conversion?我不能 100% 确定编码 - 它只是我保存到磁盘的一个文件 - 我该如何进行转换? Is there a .NET class that reads the byte order mark and can figure out the encoding for me?是否有 .NET class 可以读取字节顺序标记并可以为我找出编码?

See how-to-guess-the-encoding-of-a-file-with-no-bom-in-net .请参阅how-to-guess-the-encoding-of-a-file-with-no-bom-in-net

Since strings are Unicode, you must specify an encoding on conversion.由于字符串是 Unicode,因此您必须在转换时指定编码。 Text streams (even ReadAllText() ) have an active encoding inside, usually some sensible default.文本流(甚至ReadAllText() )内部有一个活动编码,通常是一些合理的默认值。

Try something like this:尝试这样的事情:

buffer = Encoding.Convert( Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buffer );
newString = Encoding.UTF8.GetString( buffer, 0, len );

How much do you know about the file?你对文件了解多少? Could it really be any encoding?真的可以是任何编码吗? If so, you'd need to use heuristics to guess the encoding.如果是这样,您需要使用启发式方法来猜测编码。 If it's going to be UTF-8, UTF-16 or UTF-32 then如果它将是 UTF-8、UTF-16 或 UTF-32 那么

new StreamReader(new MemoryStream(bytes), true)

will detect the encoding for you automatically.将自动为您检测编码。 Text is pretty nasty if you really don't know the encoding though.如果您真的不知道编码,则文本非常讨厌。 There are plenty of cases where you really would just be guessing.在很多情况下,您真的只是在猜测。

If File.ReadAllText will read the file correctly, then you have a couple of options.如果File.ReadAllText将正确读取文件,那么您有几个选择。

Instead of calling BeginRead , you could just call File.ReadAllText asynchronously:您可以异步调用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);
    }

Or you can create a MemoryStream from the byte array, and then use a StreamReader on that.或者,您可以从字节数组创建MemoryStream ,然后在其上使用StreamReader

There is no simple way to get the encoding, but as mentioned above use没有简单的方法来获取编码,但如上所述使用

string str = System.Text.Encoding.Default.GetString(mybytearray);

if you have no clue of what the encoding is.如果您不知道编码是什么。 If you are in europe the ISO-8859-1 is probably the encoding you have.如果您在欧洲,那么 ISO-8859-1 可能就是您拥有的编码。

string str = System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(mybytearray);

System.IO.File.ReadAllText does what you want. System.IO.File.ReadAllText 做你想做的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM