No working append byte array to existing file using visual Basic - vb.net

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()

Related

Move binary data until specific values from one file to another

I writing a Visual Basic app and stuck at one point:
I need that app read the file, select everything before DDS string, cut it from file and paste to new file.
Then after edit a DDS insert that header.
Problem is, this header before DDS have not fixed length: every file of this type have different header. I tried to mess with System.IO.FileStream but got no result.
Is this even possible to do?
The header length is not that much, a simple search pattern is probably enough.
Pass the sequence of Bytes to find inside the File and the File path to the FindHeader method.
It returns a byte array containing all the bytes collected before the specified sequence is found.
This is a simple patter matching that seeks forward until it finds the first byte that can match the specified sequence.
It then reads a buffer and compares the buffer with the sequence:
- if it's a match, returns the bytes accumulated until that point;
- if it's not, it backtracks from the current position of a [Sequence Length] - 1 positions (inside the current Stream buffer) and continues.
You can call it like this:
Dim closeSequence = New Byte() { &H44, &H44, &H53 }
Dim headerBytes = FindHeader([Source File 1 Path], closeSequence)
Now we have the Header of the first source file.
The data section of the second source file is then:
Dim sourceFile2DataStart = FindHeader([Source File 2 Path], closeSequence).Length + closeSequence.Length
Dim dataLength = New FileInfo([Source File 2 Path]).Length - sourceFile2DataStart
We need to create a third file which will contain the Header of the fist file and the data read from the second file.
' Create a read buffer. The buffer length is less than or equal to the data length
Dim bufferLength As Integer = CInt(If(dataLength >= 1024, 1024, dataLength))
Dim buffer As Byte() = New Byte(bufferLength - 1) {}
Dim read As Integer = 0
Using two FileStream objects, we create a new Destination File, write the header of the first Source File, the closeSequence that identifies the start of the data section, then we read a buffer from the second Source File and write the buffer to the Destination File:
Dim patchworkFilePath as string = [Path of the Destination File]
Using sWriter As FileStream = New FileStream(patchworkFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None),
sReader As FileStream = New FileStream([Source File 2 Path], FileMode.Open, FileAccess.Read, FileShare.None)
sReader.Seek(sourceFile2DataStart, SeekOrigin.Begin)
sWriter.Write(header1Bytes, 0, header1Bytes.Length)
sWriter.Write(closeSequence, 0, closeSequence.Length)
While True
read = sReader.Read(buffer, 0, buffer.Length)
If read = 0 Then Exit While
sWriter.Write(buffer, 0, read)
End While
End Using
The Header reader method:
Public Function FindHeader(filePath As String, headerClosure As Byte()) As Byte()
Dim byteToFind = headerClosure(0)
Dim buffer = New Byte(headerClosure.Length - 1) {}
Dim header = New List(Of Byte)(2048)
Dim read As Integer = 0
Using fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None)
While fs.Position <= (fs.Length - headerClosure.Length)
read = fs.ReadByte()
If read = byteToFind Then
fs.Read(buffer, 1, buffer.Length - 1)
buffer(0) = CByte(read)
If buffer.SequenceEqual(headerClosure) Then Exit While
fs.Seek(-(buffer.Length - 1), SeekOrigin.Current)
End If
header.Add(CByte(read))
End While
End Using
Return header.ToArray()
End Function

VB - save response as binary

Please see part of the code used to save response as a string to resultData variable:
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
It works correctly.
I have one case where the output is a binary file. How can I modify this code to save the reponse as a binary ResultData variable?
Thank you in advance for your support.
There is many ways to do that. This one, is one of those. (This one help you also to show the progress)
However (as advice) to monitoring progress there exists better approaches like Async methods etc.
In the example below I’m going to show you how to save e WebRequest as binary data.
Note that, I’m based on your code and what you want, but, as I said before there exists different better approaches.
'here the file you want to save
Dim LocalFilePath As String = "C:\Users\MyUser\Documents\FolderXYZ\yourfileName.extension"
Using reader As IO.Stream = request.GetResponse.GetResponseStream
Using writer As IO.Stream = New IO.FileStream(LocalFilePath, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)
Dim b(1024 * 2) As Byte
Dim buffer As Integer = b.Length
Do While buffer <> 0
buffer = reader.Read(b, 0, b.Length)
writer.Write(b, 0, buffer)
writer.Flush()
Loop
End Using
End Using

how to write image bytes to a text file in .net

Am trying to copy my image value to text file. my code is below.
If fldtype = "System.Byte[]" Then
Dim bits As Byte() = CType(drow(dc), Byte())
Using ms As New MemoryStream(bits)
Dim sw As New StreamWriter(ms)
Dim sr As New StreamReader(ms)
Dim myStr As String = sr.ReadToEnd()
MessageBox.Show(myStr)
fldvalue = fldvalue + "," + myStr
End Using
I find this to be one of the easiest ways to write a Byte[] to a string:
If fldtype = "System.Byte[]" Then
Dim bits As Byte() = CType(drow(dc), Byte())
Dim s As String = Convert.ToBase64String(bits)
End If
Works in reverse, too:
Dim newBytes() As Byte = Convert.FromBase64String(s)
The answer linked in the original comments could prove to be better options. Answering these questions would go a long way:
Why write an image out to text in the first place?
What do you mean to do with it once it's there?
Do you need to be able to retrieve that string and re-form the original image?
Question #3 is especially important because the information you are capturing matters when it comes to image format information. That could be lost, making it difficult to reconstitute the original image 100%.

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()

Get byte data from a file

I am using this little function to get the byte data from a file but sometimes I get errors maybe bad file or bad code or file in use?
Dim fs As System.IO.FileStream = New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim br As System.IO.BinaryReader = New System.IO.BinaryReader(fs)
Dim data() As Byte = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()
Return data
If it's a small enough file that you want all the bytes in memory in an array, the easiest way to do it is:
Dim data() as Byte = File.ReadAllBytes(filePath)