将Byte数组写入文件

use*_*934 -1 .net c#

我尝试写入byte array,txt file结果是gibrish而不是我的字节

这是我的功能:

public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
   try
   {
      // Open file for reading
      System.IO.FileStream _FileStream = 
         new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
                                  System.IO.FileAccess.Write);
      // Writes a block of bytes to this stream using data from
      // a byte array.
      _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

      // close file stream
      _FileStream.Close();

      return true;
   }
   catch (Exception _Exception)
   {
      // Error
      Console.WriteLine("Exception caught in process: {0}",
                        _Exception.ToString());
   }

   // error occured, return false
   return false;
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

"3DUf " E  _Xu  €ˆ?
=2‡¬1p% n K? C  
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 5

您的编写代码看起来不错,但更简单的解决方案:

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
   System.IO.File.WriteAllBytes(fileName, byteArray);
   return true;
}
Run Code Online (Sandbox Code Playgroud)

我试着写字节数组txt文件

在这种情况下,在某些编码中,字节数组应该是文本的正确表示.

我怀疑你在产生的步骤中有一些编码问题byteArray.