I want to write a byte array to the end of an existing file. How to append byte array to file?
4 Answers
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
Comments
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
Heinzi
If his question is explicitly tagged "vb.net", why do you assume he is after C# code?
Raghu
For some reason, formatting didnt work on the code. Excuse my brevity.
Heinzi
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.svick
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.
Raghu
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.
|