Search code examples
c#filefilestreamoffsetfilewriter

Append Byte Array at the End of an File


I would like to append an Byte Array to an existing File. It must be at the end of the File. I could already manage to write at the start of the file. (Thanks to stackoverflow ;)).

Code for that:

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;

}

Got it from here:

Link

But I need it at the end of the file

Thanks in advance.

Found the solution:

FileStream writeStream;
        try
        {
            writeStream = new FileStream(_FileName, FileMode.Append,FileAccess.Write);
            BinaryWriter writeBinay = new BinaryWriter(writeStream);
            writeBinay.Write(_ByteArray);
            writeBinay.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

Solution

  • Instead of using System.IO.FileMode.Create, use System.IO.FileMode.Append - it does exactly what you need.

    From FileMode Enumeration on MSDN:

    Append: Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.