How to append byte array to file? - vb.net

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

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

Use System.IO.FileStream class methods. Open/create a FileStream in append file mode.
System.IO.FileStream(filename,System.IO.FileMode.Append)

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

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

Related

How to decode zip file and save it in vb.net?

I am creating a project where a zip file is base 64 encoded and then the file is decoded and saved, but when I unzip the file it gives a corrupted file error.
Dim zip As New Xs_UnZipFilesCompat
''Encode()
Dim base64encoded As String
Using r As StreamReader = New StreamReader(File.OpenRead("E:\zip_test.zip"))
Dim data As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(r.ReadToEnd())
base64encoded = System.Convert.ToBase64String(data)
r.Dispose()
End Using
'decode --> write back
Using w As StreamWriter = New StreamWriter(File.Create("e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip"))
Dim data As Byte() = System.Convert.FromBase64String(base64encoded)
w.Write(System.Text.ASCIIEncoding.ASCII.GetString(data))
w.Dispose()
End Using
I can't find the solution
The encode is not correct. Specifically, this line:
Dim data As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(r.ReadToEnd())
You definitely don't want to read a file with a *.zip extension as if it were made of ASCII characters. Replace it with this:
Dim data As Byte() = System.IO.File.ReadAllBytes(fileName)
Which means you also no longer need the StreamReader, so we end up with this:
Public Function Encode(fileName As String) As String
Return Convert.ToBase64String(IO.File.ReadAllBytes(fileName))
End Function
Then the Decode would look like this:
Public Sub Decode(fileName As String, base64Data As String)
IO.File.WriteAllBytes(fileName, Convert.FromBase64String(base64Data))
End Sub
And you could call them like this:
Dim base64encoded As String = Encode("E:\zip_test.zip")
Decode("e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip", base64encoded)
Or we can write it without the methods like this:
Dim base64encoded As String = Convert.ToBase64String(IO.File.ReadAllBytes("E:\zip_test.zip"))
IO.File.WriteAllBytes("e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip", Convert.FromBase64String(base64encoded))
But it seems like that all reduces down to this:
IO.File.Copy("E:\zip_test.zip", "e:\stcRepositorio\Entrena_To_Art\Enviar\testDEco.zip")

No working append byte array to existing file using visual Basic

I have two strings, each string is a PDF etiquette, I must to write this two etiquette into a PDF file. To do this I convert a each string to a byte array (I don't know if this is the best way) and each I Write into a PDF file. When I write one etiquette into PDF file all is good, I see the etiquette, but then I try to appending the second, the result is the same, into the file is only the first etiquette. For example this code write first etiquette and all working good:
Dim fs As FileStream = New FileStream(fullFileName, FileMode.CreateNew)
fs.Close()
fs = New FileStream(fullFileName, FileMode.Append)
Dim str As String = GetPDFString(27)
Dim binaryData As Byte() = ConvertStringToByte(str)
fs.Write(binaryData, 0, binaryData.Length)
fs.Close()
but if I want to append the second etiquette in the same PDF file using this code ... this not appending.
Dim fs As FileStream = New FileStream(fullFileName, FileMode.CreateNew)
fs.Close()
fs = New FileStream(fullFileName, FileMode.Append)
Dim str As String = GetPDFString(25)
Dim str1 As String = GetPDFString(27)
Dim binaryData As Byte() = ConvertStringToByte(str)
Dim binaryData1 As Byte() = ConvertStringToByte(str1)
fs.Write(binaryData, 0, binaryData.Length)
fs.Write(binaryData1, 0, binaryData1.Length)
fs.Close()
both have the same result, and I don't understand why the second etiquette isn't appending? Thank you a lot.
Your question title suggests that you are asking about how to append a byte to a FileStream, not about PDF, and not about Base64 string conversion (which you are using in your code).
Before asking a question on StackOverflow, you need to ensure you are conveying only one problem at a time. Remove everything that is not relevant, and prepare a code sample we can use in a brand new VS project, in order to reproduce your problem and help you solve it.
Now, if your question is really about appending a byte (or a byte array) to a file, it's as simple as one line of code (or two, if you keep FileStream approach). See below link:
C# Append byte array to existing file
Also copy-pasted for your convenience here (and converted from C# to VB.NET):
Dim appendMe As Byte() = New Byte(999) {}
File.AppendAllBytes("C:\test.exe", appendMe)
Or, to avoid memory overflow, if your byte array is expected to be large enough:
Public Shared Sub AppendAllBytes(path As String, bytes As Byte())
'argument-checking here.
Using stream = New FileStream(path, FileMode.Append)
stream.Write(bytes, 0, bytes.Length)
End Using
End Sub
With this line:
fs.Write(binaryData1, binaryData.Length + 1, binaryData1.Length)
Specifically the second argument (binaryData.Length + 1), you're telling it to start appending from the wrong position of binaryData1. If it's 3 bytes long, for example, and so is binaryData, it won't append anything. It should be similar to the first .Write line:
fs.Write(binaryData1, 0, binaryData1.Length)
So it appends all of binaryData1. It will still append it after binaryData - you don't need to specify the length of the preceeding binaryData in this line.
Alternatively, bypassing the above entirely, concatenate your two strings before encoding/writing them to the file:
Dim fs As FileStream = New FileStream(fullFileName, FileMode.CreateNew)
fs.Close()
fs = New FileStream(fullFileName, FileMode.Append)
Dim str As String = GetPDFString(id, token, depot, 25)
Dim str1 As String = GetPDFString(id, token, depot, 27)
Dim binaryData As Byte() = Convert.FromBase64String(str & str1) 'concatenate strings
fs.Write(binaryData, 0, binaryData.Length)
fs.Close()

Can I Convert A Byte() to a string?

I need a solution to my current code, I am trying to save text to a file from a Text Box, and add a string to it.
My following code is:
Dim fs As FileStream = File.Create(fileName.Text)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(CodeBox.Text)
Dim Code = "-- Made with LUA Creator by Sam v1.9
" + info
fs.Write(Code, 0, Code.Length)
fs.Close()
MsgBox("File saved as " + fileName.Text)
But Visual Studio says that I cannot use "+" operator with strings & bytes:
Error BC30452 Operator '+' is not defined for types 'String' and 'Byte()'.
Anyone have a solution?
Sorry if this is a duplicate, I couldn't find it anywhere here so I just asked myself. Thanks.
"Can I Convert A Byte() to a string?" Short answer is yes, but that doesn't look like what you're really wanting to do.
You're trying to concatenate a String with a Byte array, which Dim Code has no idea what the end result is supposed to be.
FileStream.Write() requires a Byte array so you can try a couple of things
Concatenate the string from the TextBox with your "header" information then turn it into a Byte array.
Dim fs As FileStream = File.Create(fileName.Text)
' Add text to the file.
Dim Code As Byte() = New UTF8Encoding(true).GetBytes("-- Made with LUA Creator by Sam v1.9 " & CodeBox.Text)
fs.Write(Code, 0, Code.Length)
fs.Close()
Write your "header" information, then write the Textbox information
Dim fs As FileStream = File.Create(fileName.Text)
' Add text to the file.
Dim header As Byte() = New UTF8Encoding(true).GetBytes("-- Made with LUA Creator by Sam v1.9 ")
Dim info As Byte() = New UTF8Encoding(True).GetBytes(CodeBox.Text)
fs.Write(header, 0, header.Length)
fs.Write(info, 0, info.Length)
fs.Close()

Read Data From The Byte Array Returned From Web Service

I have a web service,which return data in byte array.Now i want to read that data in my console project.How can i do that,i already add the desire references to access that web service.I am using vb.net VS2012.Thanks.My web service method is as follow.
Public Function GetFile() As Byte()
Dim response As Byte()
Dim filePath As String = "D:\file.txt"
response = File.ReadAllBytes(filePath)
Return response
End Function
Something like,
Dim result As String
Using (Dim data As New MemoryStream(response))
Using (Dim reader As New StreamReader(data))
result = reader.ReadToEnd()
End Using
End Using
if you knew the encoding, lets say it was UTF-8 you could do,
Dim result = System.Text.UTF8Encoding.GetString(response)
Following on from your comments, I think you are asserting this.
Dim response As Byte() 'Is the bytes of a Base64 encoded string.
So, we know all the bytes will be valid ASCII (because its Base64,) so the string encoding is interchangable.
Dim base64Encoded As String = System.Text.UTF8Encoding.GetString(response)
Now, base64Encoded is the string Base64 representation of some binary.
Dim decodedBinary As Byte() = Convert.FromBase64String(base64Encoded)
So, we've changed the encoded base64 into the binary it represents. Now, because I can see that in your example, you are reading a file called "D:/file.txt" I'm going to make the assumption that the contents of the file is a character encoded string, but I don't know the encoding of the string. The StreamReader class has some logic in the constructor that can make an educated guess at character encoding.
Dim result As String
Using (Dim data As New MemoryStream(decodedBinary))
Using (Dim reader As New StreamReader(data))
result = reader.ReadToEnd()
End Using
End Using
Hopefully, now result contains the context of the text file.

RAW Data from embedded resource image

I am trying to retrieve an image from an Embedded resource, and displaying it in its RAW DATA format (i.e. -> junk text data).
Basically, I am running into a wall with everything I attempt.
Can someone show me how to do this properly?
You can use the following msdn ref
System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(fileName)
That will give you a Stream which you can then use code cite to convert to a byte array which is pretty much the raw data.
private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()
Return fileData
End Function