-1

I'm trying to write a byte array to txt file and the result is gibberish 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  
LiamJM
  • 172
  • 12
user1860934
  • 417
  • 2
  • 9
  • 22
  • What are you expecting the output to look like? – Blorgbeard Mar 07 '14 at 10:34
  • How do you generate `_ByteArray`? – Robert Fricke Mar 07 '14 at 10:37
  • Also, your naming convention is strange, locals should be `camelCase`, no underscores. And returning a bool to indicate success/failure is also frowned upon in .Net. Exceptions are supposed to be the method used to indicate failure. I would just remove that try/catch - let any error bubble up until you can actually meaningfully handle it, even if that's just a top-level handler that logs it and quits. – Blorgbeard Mar 07 '14 at 10:39
  • 1
    your code is correct for its purpose, show us `_ByteArray` variable content. – hmnzr Mar 07 '14 at 10:40
  • This content is packet byte[] from PcapDotNet project (packet.buffer return byte[]) – user1860934 Mar 07 '14 at 10:44
  • Possible duplicate of [Can a Byte\[\] Array be written to a file in C#?](https://stackoverflow.com/questions/381508/can-a-byte-array-be-written-to-a-file-in-c) – James Lawruk Jul 03 '18 at 13:23

2 Answers2

7

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.

H H
  • 263,252
  • 30
  • 330
  • 514
0
  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
ili
  • 722
  • 1
  • 4
  • 15