VB.net invalid length for a base 64 char array or string - vb.net

I have an issue with conversion from a base-64 string to normal, readable text. I did some research and found that base 64 strings have to be of a length that is a multiple of 4. So I used padRight to give it a valid length, but I keep getting the same error. For example, I enter "hi" and it encodes as "⚫aGk====", which seems like 8 characters to me (which is obviously a multiple of 4). When I try to read it, it reads in with a length of 1.
I'm also using a custom file extension that I just called ".bgs". I'm not sure if that does anything. Writing to this file as a base64 string and reading/decoding it is the only thing I'm trying to do.
Here is my code:
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using bs As New BinaryWriter(File.Open("saveFile.bgs", FileMode.Create))
Dim originText As String = TextBox1.Text
Dim cipherText As String
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(originText)
cipherText = Convert.ToBase64String(byteArray)
Dim realLength As Integer = cipherText.Length() + 1
Dim len As Integer = (realLength Mod 4)
If (len > 0) Then bs.Write(cipherText.PadRight(realLength + (3 - len), "="))
bs.Close()
End Using
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Using bs As New BinaryReader(File.Open("saveFile.bgs", FileMode.Open))
Dim cipherText2 As String = bs.Read()
Dim originText2 As String = "Failed"
TextBox2.Text = cipherText2.Length() 'reports length of 1
Try
Dim byteArray2 As Byte() = Convert.FromBase64String(cipherText2)
originText2 = System.Text.Encoding.UTF8.GetString(byteArray2)
Catch ex As Exception
End Try
'TextBox2.Text = originText2
End Using
End Sub
Any help is much appreciated!
Update: it looks like the first character (the dot in the case above) seen in the .bgs file when I open it with notepad controls the contents of cipherText2, which is just a number, explaining why the length is so low.

Base64 encodes using only printable ASCII characters.
You are seeing the dot because you are using binary writer which prefixes strings with their length when writing to file.
Then you are using Read instead of ReadString so you read the string length as a number (which is then implicitly converted to string because you are not using Option Strict On like you should).
You can fix it by using ReadString instead of Read, but it would be easier if you used a text writer.
You also should not try to pad results of ToBase64String. It already gives you the correct string.
I would rewrite your code as:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim originText As String = TextBox1.Text
Dim cipherText As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(originText))
System.IO.File.WriteAllText("saveFile.bgs", cipherText, System.Text.Encoding.ASCII)
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Dim cipherText2 As String = System.IO.File.ReadAllText("saveFile.bgs", System.Text.Encoding.ASCII)
Dim originText2 As String = "Failed"
originText2 = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(cipherText2))
'TextBox2.Text = originText2
End Sub

Related

How to compare textbox value to txt file

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim linenumber0 As Integer
linenumber0 = 0
Dim mass As Double
mass = (File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
If (Math.Abs((cDbl(TextBox1.Text) - mass < 0.5) Then
TextBox1.BackColor = Color.Green
End If
Im getting an error conversing from string to double is not valid. It is probably a simple solution but i cant see it right now
Your error occurs because the data read from the file is a String, however you are attempting to assign it to a variable declared as Double.
You can use TryParse to convert the String to Double, avoid errors and provide appropriate feedback.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lineNumber0 As Integer
Dim mass As Double
Dim input As Double
If Double.TryParse(File.ReadAllLines("225.txt").ElementAt(linenumber0), mass) Then
If Double.TryParse(TextBox1.Text, input) AndAlso Math.Abs(input - mass) < 0.5 Then
TextBox1.BackColor = Color.Green
End If
Else
'Bad file input
End If
'...
End Sub
I think that when you set the value to mass is catching a String, so parse it with a simple CDbl, like this
mass = cDbl(File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
I supose that with this fix it will works.
Just in case, surround it with a TRY CATCH in case what it reads is not valid

Replace text Character Shift-JIS

I have a problem with Shift Jis character. I used the following code but it is not working:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim line As String
Using sr As StreamReader = New StreamReader("C:\2\File.txt", System.Text.Encoding.GetEncoding(932))
line = sr.ReadToEnd
line.Replace("チ", "Chi")
End Using
End Sub
End Class
Thanks in advance. I hope you understand my problem.
I think your only problem is that you are not storing the return value from the replace-method. So what I think you want is:
line = line.Replace("チ", "Chi")
If you want to replace the content back to the file, you can do it with something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filename As String = "C:\2\File.txt"
Dim line As String
Dim encoding As System.Text.Encoding = System.Text.Encoding.GetEncoding(932)
' You could replace the using-block with:
' line = File.ReadAllText(filename, encoding)
Using sr As StreamReader = New StreamReader(filename, encoding)
line = sr.ReadToEnd
line.Replace("チ", "Chi")
End Using
File.WriteAllText(filename, line, encoding)
End Sub

VB.NET Serial Port reading HEX data and insert in the textbox

I want to read the data from UHF RFID reader that is connected on one of my com port, the data should be in HEX and must be a complete HEX that should be pasted in the textbox in my windows form application that I made in VB.NET.
Kindly help me I am new in VB.NET Programming.I need a vb.net code for this task:
My code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each s In System.IO.Ports.SerialPort.GetPortNames()
ComboBox1.Items.Add(s)
Next s
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex = -1 Then
MessageBox.Show("Please select a port")
Exit Sub
Else
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.PortName = ComboBox1.SelectedItem.ToString
SerialPort1.Open()
End If
End Sub
Private Shared buffer As String = ""
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Try
Dim rcv As String = _SerialPort1.ReadExisting()
buffer = String.Concat(buffer, rcv)
Dim hexVal As Integer
hexVal = Convert.ToInt32(rcv, 16) '16 specifies the base
txtReceived.Text = hexVal
Catch ex As Exception
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SerialPort1.Close()
End Sub
End Class
I see your problem..
the line
hexVal = Convert.ToInt32(c, 16) '16 specifies the base
is trying to convert a character to int32, but the function is assuming that the incoming value is already hexadecimal and you're getting a completely wrong answer.
Incidentally, your data is 8 bit binary and your serial port reader reads each 8 bits as a char type.
What you need is to use the VB built in function Hex, which takes an integer/byte (in this case the ascii code of each character) and returns a hex value as a string so
Dim x As Integer = 15
Dim s As String = hex(x)
will assign "F" to the string
All well and good. However, If you want a 2 digit hex string, you'll need to check if the returned string is only one character and if it is, add a "0" to the beginning.
So, your lines
Dim hexVal As Integer
hexVal = Convert.ToInt32(rcv, 16) '16 specifies the base
txtReceived.Text = hexVal
should be replaced with ..
Dim hexVal As string =""
For Each c As Char In rcv
hexVal = heval & AsciiCharToHexSring(c)
Next
txtReceived.Text = hexVal
and add this function to convert the character and add a "0" if necessary ..
Private Function AsciiCharToHexSring(s As Char) As String
Dim hexdigit As String = Hex(Asc(s))
If hexdigit.Length = 1 Then
hexdigit = "0" & hexdigit
End If
Return hexdigit
End Function
If you don't need a 2 digit hex number every time, just delete the If..End If block

How to filter text out of a textbox in VB.NET

I have a problem while making my skype resolver, when it resolves an ip the text comes out like this ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,SERVER 1: 124.169.179.116 - Skype4Resolver.com" (btw the "," are spaces... stackoverflow doesn't show them.) when this happeneds it makes the text go unseen and out of the textbox. can anyone help? i want to filter out the spaces and anything that isnt part of the ip.
here is my code:
Imports System.Net
Public Class Form2
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
WebRequest.Create("http://api.skype4resolver.com/api.php?key=free&username=" + TextBox1.Text + "&server=1")
TextBox2.Text = New System.Net.WebClient().DownloadString("http://api.skype4resolver.com/api.php?key=free&username=" + TextBox1.Text + "&server=1")
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
End Sub
End Class
Use a trim function on the returned string!
http://msdn.microsoft.com/en-us/library/system.string.trimstart(v=vs.110).aspx
Depending on what you want, try a regular expression (regexp based on RegEx for an IP Address) or split on the colon (as per http://msdn.microsoft.com/en-us/library/tabh47cf%28v=vs.110%29.aspx)
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim Input As String = " SERVER 1: 124.169.179.116 - Skype4Resolver.com"
Dim ResultSplit As String = Input.Split(":")(1)
Console.WriteLine(String.Format("Split token [{0}]", ResultSplit)) ' Split token [124.169.179.116 - Skype4Resolver.com]
Dim IpRegex As Regex = New Regex("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
If (IpRegex.IsMatch(Input)) Then
Dim ResultRegex As MatchCollection = IpRegex.Matches(Input)
Console.WriteLine(String.Format("Regexp match [{0}]", ResultRegex(0))) ' Regexp match [124.169.179.116]
End If
Console.WriteLine()
End Sub
End Module
which in your specific use case becomes
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Input As String = TextBox1.Text
Dim IpRegex As Regex = New Regex("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
If (IpRegex.IsMatch(Input)) Then
Dim ResultRegex As MatchCollection = IpRegex.Matches(Input)
WebRequest.Create("http://api.skype4resolver.com/api.php?key=free&username=" + ResultRegex(0) + "&server=1")
TextBox2.Text = ResultRegex(0)
End If
End Sub
Regular expressions are very powerful for text processing. Make a point of learning them eventually. You want to discard the part that you don't want, but instead I go find the part that I do want. So it won't matter if the spaces are commas or if the server name is in a foreign language: this regular expression will find the first thing that looks like an IP address and match it.

Find the index of a char in string?

I have a string that goes like "abcdefg..."
I would like to find the index where the letter d is at, so I can get the number 3.
I managed to do it by looping through each letter in the string, but that doesn't sound very convenient. Is there another way?
The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:
Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then
End If
Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains("d") Then
numberString = myString.IndexOf("d")
End If
End Sub
Another sample with TextBox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim myString As String = "abcdef"
Dim numberString As String = String.Empty
If myString.Contains(me.TextBox1.Text) Then
numberString = myString.IndexOf(Me.TextBox1.Text)
End If
End Sub
Regards
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1