将字节数组写入txt文件会产生奇怪的字符(c#)

时间:2016-06-02 07:54:47

标签: c# file filestream

我有一个包含不同数字(0-256)的大字节数组。首先,我使用File.WriteAllText创建.txt文件并写几行文本。之后我想在文本之后将我的字节数组保存到此文件中,但是当我用记事本打开它时,其中有奇怪的字符。这是编码的问题吗?

String filename = "filename.txt";
String text = "Some metadata........" + Environment.NewLine;
System.IO.File.WriteAllText(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), filename), text);

using (var stream = new FileStream(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), filename), FileMode.Append))
    {
        stream.Write(data_tmp, 0, data_tmp.Length);
        stream.Close();
    }

这是我看到的,当我用记事本打开.txt时:

一些元数据........

øÀþð?øÀüà2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþð?øÀþà?øÀüàø€üàðüÀ〜d?OA〜d?øÀþà?THA 2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüà2 O€UAD€UA〜d?UA〜d?øÀþð?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþà?øÀüà2 O €UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþð?øÀþà2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüà2 O€UAD €UA〜d?UA〜d?øÀþð?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþà?øÀüà2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüàø€üàðüà〜d?UA 〜d?øÀþð?øÀþà?øÀüàø€üàðüÀ〜d?OA〜d?øÀþà?øÀüà2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþð?øÀþà 2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþð?øÀþà?øÀüàø€üàðüÀ〜d?OA〜d?øÀþà?øÀüà2 O€UAD€ü 〜DUA〜d?OA〜d?øÀþà?øÀüàø€üàðüà〜d?UA〜d?øÀþð?øÀþà2 O€UAD€UA〜DUA〜d?OA〜d?øÀþà?øÀüà2 O€UAD€UA〜d ?üÀ~ð?øÀþð?øÀþà?ÖÀàà€€üàðüà~ð?üÀ~ð?øÀþà?øÀüà?ø€€€€€€€€......

2 个答案:

答案 0 :(得分:1)

你的问题很模糊。您可能希望将编码字节转换为某些文本,比如十六进制表示吗?

   String text = 
     "Some metadata........" + 
      Environment.NewLine + 
      String.Join(" ", data_tmp.Select(x => x.ToString("x2"))); // <- encoding 

   System.IO.File.WriteAllText(..., text);

而没有FileStream?所以你会有这样的事情:

   Some metadata........
   ab 45 25 e8 f0 03     // <- encoded array 

答案 1 :(得分:0)

如果你想看到的只是该数组中字节的十进制表示,你必须将它们转换为该十进制数,然后转换为字符串,然后转换为该字符串的字节表示。

您现在正在做的是将数组中的字节解释为UTF8(标准编码)字符表示。

假设字节的十进制表示是你想要的,你可以这样做:

        Encoding utf8 = Encoding.UTF8;
        byte[] data_tmp = new byte[] { 1, 2, 3, 4 };
        String filename = "filename.txt";
        String text = "Some metadata........" + Environment.NewLine;
        System.IO.File.WriteAllText(
            System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), filename), text, utf8);

        using (var stream = new FileStream(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), filename), FileMode.Append))
        {
            IEnumerable<byte[]> bytesToStringedInUtf8 = data_tmp.Select(b => utf8.GetBytes(((int)b).ToString()));
            foreach (byte[] byteToStringedInUtf8 in bytesToStringedInUtf8)
            {
                stream.Write(byteToStringedInUtf8, 0, byteToStringedInUtf8.Length);
            }
            stream.Close();
        }

输出为:

一些元数据........

1234