简体   繁体   中英

Write Byte array to file

I try to write byte array to txt file and the result is gibrish instead of my bytes

This is my function:

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;
}

And the result:

"3DUf " E  _Xu  €ˆ‏
=2‡¬1p% n Kפ C  

Your writing code looks OK but the much simpler solution:

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

I try to write byte array to txt file

In that case the byte-array should be the correct representation of a text, in some encoding.

I suspect you have some encoding issues in the steps that produce byteArray .

  1. It is better to use using for file stream, or call Close() in finally block
  2. There is no "text files". Text is just set of bytes, bytes are represented as signs with encoding (ASCII, Unicode, UTF8, etc.). When you are writing bytes system writes them as is, and when you are looking the file with notepad it shows it with encoding (it reads 0x31 and shows 1, and so on).
  3. If you are trying to write text file, look forward for File.WriteAllText() method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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