Can I Convert A Byte() to a string? - vb.net

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

Related

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%.

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

Loading Picture Stored in Access Database into Program VB.NET

I have an Access Database linked with a VB project through a data source. In the database on one of the tables, I have an OLE Object field. I have saved pictures in .BMP format and .JPG format in this field. The problem I am encountering is loading this image into my application. This is what I would like to be able to do:
ButtonMeal1.BackgroundImage = IPOSDBDataSet.Meals.Rows(0).Item(5)
Where Item(5) is the column of the row where the image is stored.
Is there another way of doing this. Do I have to load the picture into the program by storing it as a variable, and then using that to change the background image of the button. There are no clear answers on the internet regarding my issue. Please help!
EDIT 1:
After doing some more research, I found some code and adjusted it to try fix my problem.
Dim ImageByteArray As Byte() = CType(IPOSDBDataSet.Meals.Rows(0).Item(5), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(ImageByteArray)
Dim MyImage As Image = Drawing.Image.FromStream(ImageMemoryStream)
PictureBox1.Image = MyImage
However, I receive the error "Parameter is Not Valid" with the 3rd line of the code. Would anyone be able to tell me how I could adjust my code to fix this issue, or tell me if I am doing something completely wrong?
EDIT 2:
I keep on changing the code around, but the error is always "Parameter is not valid.". What parameter is not valid?
EDIT 3:
No matter what I change it to, the error still persists. What is this parameter that is causing all my issues?
Dim ImageByteArray As Byte() = CType(IPOSDBDataSet.Meals.Rows(0).Item(5), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(ImageByteArray)
Dim ImageStream As Stream = ImageMemoryStream
Dim MyImage As Image = Drawing.Image.FromStream(ImageStream)
PictureBox1.Image = MyImage
EDIT 4:
Can anyone please help? I really need to be able to implement this into my program. Is there any other possible way of storing images in an access database, and importing them into my vb.net program?
Credit goes to TnTinMan from CodeProject for the answer. Hopefully this helps someone else:
Dim ImageByteArray As Byte() = CType(DataSet.Table.Rows(RowNo).Item(ItemNo), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(GetImageBytesFromOLEField(ImageByteArray))
Dim MyImage As Image = Drawing.Image.FromStream(ImageMemoryStream)
Friend Shared Function GetImageBytesFromOLEField(ByVal oleFieldBytes() As Byte) As Byte()
Dim BITMAP_ID_BLOCK As String = "BM"
Dim JPG_ID_BLOCK As String = ChrW(&HFF).ToString() & ChrW(&HD8).ToString() & ChrW(&HFF).ToString()
Dim PNG_ID_BLOCK As String = ChrW(&H89).ToString() & "PNG" & vbCrLf & ChrW(&H1A).ToString() & vbLf
Dim GIF_ID_BLOCK As String = "GIF8"
Dim TIFF_ID_BLOCK As String = "II*" & ChrW(&H0).ToString()
Dim imageBytes() As Byte
' Get a UTF7 Encoded string version
Dim u7 As System.Text.Encoding = System.Text.Encoding.UTF7
Dim strTemp As String = u7.GetString(oleFieldBytes)
Dim st2 As String = System.Text.Encoding.UTF8.GetString(oleFieldBytes)
' Get the first 300 characters from the string
Dim strVTemp As String = strTemp.Substring(0, 300)
' Search for the block
Dim iPos As Integer = -1
If strVTemp.IndexOf(BITMAP_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(BITMAP_ID_BLOCK)
ElseIf strVTemp.IndexOf(JPG_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(JPG_ID_BLOCK)
ElseIf strVTemp.IndexOf(PNG_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(PNG_ID_BLOCK)
ElseIf strVTemp.IndexOf(GIF_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(GIF_ID_BLOCK)
ElseIf strVTemp.IndexOf(TIFF_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(TIFF_ID_BLOCK)
Else
Throw New Exception("Unable to determine header size for the OLE Object")
End If
' From the position above get the new image
If iPos = -1 Then
Throw New Exception("Unable to determine header size for the OLE Object")
End If
imageBytes = New Byte(CInt(oleFieldBytes.LongLength - iPos - 1)) {}
Array.ConstrainedCopy(oleFieldBytes, iPos, imageBytes, 0, oleFieldBytes.Length - iPos)
Return imageBytes
End Function
There isn't really such a thing as an 'image' stored in an Access table, only a binary stream. Therefore, the left hand side of your expression doesn't know that the right hand side is providing an image. You would have to stream the binary stream into a stream in VB.NET, then use System.Graphics methods to make it into a BMP or PNG or whatever. You could assign that object to the button.
still show error: index and length must refer to a location within the string.Parameter name: len

Search/Replace in VB.NET

Been following the threads for sometime as a novice (more of a newbie) but am now starting to do more.
I can read how to open a text file but am having trouble understanding the .replace functionality (I get the syntax just can't get it to work).
Scenario:
Inputfile name = test_in.txt
replace {inputfile} with c:\temp\test1.txt
I'm using test.txt as a template for a scripting tool and need to replace various values within to a new file called test_2.txt.
I've got variables defining the input and output files without a problem, I just can't catch the syntax for opening the new file and replacing.
You really have not given us that much to go on. But a common mistake in using String.Replace is that it makes a copy of the source which needs to be saved to another variable or else it will go into the bit bucket. So in your case, something like this should work.
Dim Buffer As String 'buffer
Dim inputFile As String = "C:\temp\test.txt" 'template file
Dim outputFile As String = "C:\temp\test_2.txt" 'output file
Using tr As TextReader = File.OpenText(inputFile)
Buffer = tr.ReadToEnd
End Using
Buffer = Buffer.Replace("templateString", "Hello World")
File.WriteAllText(outputFile, Buffer)
Try something like this:
Dim sValuesToReplace() As String = New String() {"Value1", "Value2", "Value3"}
Dim sText As String = IO.File.ReadAllText(inputFilePath)
For Each elem As String In sValuesToReplace
sText = sText.Replace(elem, sNewValue)
Next
IO.File.WriteAllText(sOutputFilePath, sText)
It depends if you want to replace all values with only one value, or with different values for each. If you need different values you can use a Dictionary:
Dim sValuesToReplace As New Dictionary(Of String, String)()
sValuesToReplace.Add("oldValue1", "newValue1")
sValuesToReplace.Add("oldValue2", "newValue2")
'etc
And then loop throgh it with:
For Each oldElem As String In sValuesToReplace.Keys
sText = sText.Replace(oldElem, sValuesToReplace(oldElem))
Next

Receiving 'The input is not a complete block' error, tried everything I can find on google. Rjindael Encryption in .NET

Mornin', I'm trying to just get basic encryption working using System.Security.Cryptography.RjindaelManaged. I have google for this error and cannot find the problem, or what I am doing wrong. All I am attempting to do is encrypt a string, and then decrypt a string.
Following is my code, and any help would be appreciated.
Imports System.Security.Cryptography
Imports System.Text
Public rj As New RijndaelManaged
Try
rj.Padding = PaddingMode.None
rj.GenerateKey()
rj.GenerateIV()
Dim curProvider As New AesCryptoServiceProvider
Dim curEncryptor As ICryptoTransform
Dim memEncStream As New MemoryStream
Dim cryptoEncStream As CryptoStream
curEncryptor = curProvider.CreateEncryptor(rj.Key, rj.IV)
cryptoEncStream = New CryptoStream(memEncStream, curEncryptor, CryptoStreamMode.Write)
Dim startingBytes() As Byte = Encoding.ASCII.GetBytes("This is a test")
Debug.Print("before length: " & startingBytes.Length)
Debug.Print("before text: " & Encoding.ASCII.GetString(startingBytes))
EcryptoEncStream.Write(startingBytes, 0, startingBytes.Length)
cryptoEncStream.FlushFinalBlock()
memEncStream.Position = 0
Dim theBytes(memEncStream.Length) As Byte
memEncStream.Read(theBytes, 0, memEncStream.Length)
memEncStream.Flush()
memEncStream.Close()
cryptoEncStream.Close()
Debug.Print("How long? " & theBytes.Length)
Debug.Print("Data: " & Encoding.ASCII.GetString(theBytes))
Dim curDecryptor As ICryptoTransform
curDecryptor = curProvider.CreateDecryptor(rj.Key, rj.IV)
Dim memDecStream As New MemoryStream
Dim cryptoDecStream As CryptoStream
curDecryptor = curProvider.CreateDecryptor(rj.Key, rj.IV)
cryptoDecStream = New CryptoStream(memDecStream, curDecryptor, CryptoStreamMode.Write)
Dim endingBytes() As Byte = theBytes
Debug.Print("before length: " & theBytes.Length)
Debug.Print("before text: " & Encoding.ASCII.GetString(theBytes))
cryptoDecStream.Write(theBytes, 0, theBytes.Length)
cryptoDecStream.FlushFinalBlock()
memDecStream.Position = 0
Dim endBytes(memDecStream.Length) As Byte
memDecStream.Read(theBytes, 0, memDecStream.Length)
memDecStream.Flush()
memDecStream.Close()
cryptoEncStream.Close()
Debug.Print("How long? " & endBytes.Length)
Debug.Print("Data: " & Encoding.ASCII.GetString(endBytes))
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
You have overridden the PaddingMode and set it None. Why? Leave the PaddingMode to its default value of PaddingMode.PKCS7 unless you have a good reason to change it and you understand padding in a block cipher.
It appears that the problem is the length of the data that you are passing to the decryption stream. If you change the declaration of theBytes from this:
Dim theBytes(memEncStream.Length) As Byte
To this:
Dim theBytes(memEncStream.Length - 1) As Byte
Then it runs fine (at least it did for me). I'm not a VB wizard at all, but I think the array declaration is one byte longer than the given size (I think it is 0 to N). With that extra byte passed to the decryption stream, it does not work.
And I'm sure you will see it soon enough, but your printing of the final decrypted text is not quite right. It is printing theBytes instead of endBytes.