1

I want to write a byte array to the end of an existing file. How to append byte array to file?

4 Answers 4

2

Here is the solution. Just use the following sub and provide the parameters as required:

Parameters description:

FilepathToAppendTo is the filepath you need to append the byte array

Content is your byte array

Private Sub AppendByteToDisk(ByVal FilepathToAppendTo As String, ByRef Content() As Byte)
    Dim s As New System.IO.FileStream(FilepathToAppendTo, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)
    s.Write(Content, 0, Content.Length)
    s.Close()
End Sub
Sign up to request clarification or add additional context in comments.

Comments

2

Use System.IO.FileStream class methods. Open/create a FileStream in append file mode.

System.IO.FileStream(filename,System.IO.FileMode.Append)

Comments

0
Dim bufData As Byte()

' write the entire buffer in one line of code
My.Computer.FileSystem.WriteAllBytes("BinaryFile.DAT", bufData, append := True)

Comments

-1

Assumptions.

  • You want to use UTF8 encoding.
using( var stream = File.AppendText(@"D:\test.txt"))
{
    stream.WriteLine(Encoding.UTF8.GetString( b ) );
}

VB Version:

Using stream = File.AppendText("D:\test.txt")
    stream.WriteLine(Encoding.UTF8.GetString(b))
End Using

7 Comments

If his question is explicitly tagged "vb.net", why do you assume he is after C# code?
For some reason, formatting didnt work on the code. Excuse my brevity.
I will excuse your brevity, but not the content of your answer. ;-) You are converting the byte array to an ASCII-encoded string, and then convert this back into UTF-8 (see the documentation of AppendText). That's completely unnecessary. Just open the file with new FileStream and write the byte array directly with FileStream.Write. No need to do any (re-)encoding.
It's not just unnecessary, it's wrong. If there are any bytes above 127, the bytes written to the file will be different that what is in the array.
I had my mouse over for a second & method signature poped up on the method and I saw UTF-8 from the corner of my eye whilst typing and dont know why I decided to write ASCII in assumptions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.