Visual Basic Reading Binary/Hex - vb.net

I'm trying to read a list of item names from a bin file but getting an empty/null values when I try console write:
Hex Screenshot
The data are a list of item name/information that later planning to put in a listview. I'm putting an offset to binary reader below:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim path As String = "C:\Users\USER\PATH\TO\file.bin"
Using reader As New IO.BinaryReader(File.Open(path, FileMode.Open))
reader.BaseStream.Position = Convert.ToInt64(502004)
For x = reader.BaseStream.Position To 502173 - 1
Console.WriteLine(reader.ReadString())
Next
End Using
Console.WriteLine("End")
End Sub

Related

Could someone explain where are the errors in this code in vb.net

I'm new to this site and also a newbee in vb.net, I created a simple form in vb.net, a form with 3 buttons, by clicking Button1 Species1.txt is created, and by clicking Button2 the lines in Species1.txt are copied in a String Array called astSpecies(), and by Button3 the String Array is copied in a new file, named Species2.txt, below is the code.
Public Class Form4
Dim astSpecies() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species1.txt", True)
myStreamWriter.WriteLine("Pagasius pangasius")
myStreamWriter.WriteLine("Meretrix lyrata")
myStreamWriter.WriteLine("Psetta maxima")
myStreamWriter.WriteLine("Nephrops norvegicus")
myStreamWriter.WriteLine("Homarus americanus")
myStreamWriter.WriteLine("Procambarus clarkii")
myStreamWriter.Close()
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myStreamReader = New StreamReader("C:\Users\Administrator\Documents\species1.txt")
Dim i As Integer
Dim stOutput As String
stOutput = ""
Do While Not myStreamReader.EndOfStream
astSpecies(i) = myStreamReader.ReadLine
stOutput = stOutput & astSpecies(i) & vbNewLine
i = i + 1
Loop
myStreamReader.Close()
MsgBox(stOutput)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species2.txt", True)
Dim o As Integer
Do While o <= astSpecies.Length
myStreamWriter.WriteLine(astSpecies(o))
o = o + 1
Loop
myStreamWriter.Close()
End Sub
End Class
First of all, you should make a few settings when it comes to VB.Net. 1.) set Option Strict to On 2.) remove the VB6 namespace. VB6 is the old Visual Basic. There are many functions in this that are inefficient from today's perspective. So please do not write MsgBox() but MessageBox.Show("").
(If you still need control characters such as NewLine or Tab, you can set a selective reference with Imports Microsoft.VisualBasic.ControlChars. Sounds contradictory, but it is useful, because why should you also write ChrW(9), it is not legible.)
I quickly started a project myself and wrote whatever you wanted.
I still don't quite understand why you first write things into a text file, then read them out, and then write that into a second text file – I want to say: where do the strings originally come from? The strings must have been there already? Anyway, I filled a List(of String) in the Button2_Click procedure. This has the advantage that you don't have to know in advance how many strings are coming, and you can sort them later and so on ...
You should also discard all Writers when you no longer need them. So use Using. Otherwise it can happen that the written files are not discarded and you can no longer edit the file.
Imports Microsoft.VisualBasic.ControlChars
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class FormMain
Private Path As String = ""
Private allLines As New List(Of String)
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BackColor = Color.FromArgb(161, 181, 165)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using OFolderD As New CommonOpenFileDialog
OFolderD.Title = "Ordner auswählen"
OFolderD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
OFolderD.IsFolderPicker = True
If OFolderD.ShowDialog() = CommonFileDialogResult.Ok Then
Path = OFolderD.FileName
Else
Return
End If
End Using
Path &= "\Data.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True)
txtfile.WriteLine("Pagasius pangasius")
txtfile.WriteLine("Meretrix lyrata")
txtfile.WriteLine("Psetta maxima")
txtfile.WriteLine("Nephrops norvegicus")
txtfile.WriteLine("Homarus americanus")
txtfile.WriteLine("Procambarus clarkii")
txtfile.Close()
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Path, System.Text.Encoding.UTF8)
If RAT.Length = 0 OrElse RAT.Length = 1 Then
MessageBox.Show("The File only contains 0 or 1 characters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand)
Return
End If
allLines.AddRange(RAT)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Pfad_txt As String = Path.Substring(0, Path.LastIndexOf("\"c)) & "\Data2.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Pfad_txt, True)
For Each Line As String In allLines
txtfile.WriteLine(Line)
Next
txtfile.Close()
End Using
End Sub
End Class
By the way: I use a FolderBrowserDialog in the Button1_Click procedure. This should be done so that the program also runs properly on other PCs. In order to be able to use the FBD, you have to download Microsoft.WindowsAPICodePack.Dialogs in Visual Studio's own Nuget package manager.
how to set Option Strict to On
How to uncheck VB6.
how to install FolderBrowserDialog in Visual Studio
Button1
If you want to use a StreamWriter it should be disposed. Classes in the .net Framework that have a Dispose method may use resources outside of the framework which need to be cleaned up. The classes shield you from these details by provided a Dispose method which must be called to properly do the clean up. Normally this is done with Using blocks.
I used a string builder which saves creating and throwing away a string each time you change the string. You may have heard that strings are immutable (cannot be changed). The StringBuilder class gets around this limitation. It is worth using if you have many changes to your string.
The File class is a .net class that you can use to read or write files. It is not as flexible as the stream classes but it is very easy to use.
Button 2
When you declared your Array, you declared an array with no elements. You cannot add elements to an array with no space for them. As Daniel pointed out, you can use the .net class List(Of T) The T stands for Type. This is very good suggestion when you don't know the number of elements in advance. I stuck with the array idea by assigning the array returned by File.ReadAllLines to the lines variable.
You get the same result by simply reading all the text and displaying it.
Button 3
Again I used the File class here which allows you to complete your task in a single line of code. Using 2 parameters for the String.Join method, the separator string and the array to join, we reproduce the original file.
Private SpeciesPath As String = "C:\Users\maryo\Documents\species1.txt"
Private lines As String()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder
sb.AppendLine("Pagasius pangasius")
sb.AppendLine("Meretrix lyrata")
sb.AppendLine("Psetta maxima")
sb.AppendLine("Nephrops norvegicus")
sb.AppendLine("Homarus americanus")
sb.AppendLine("Procambarus clarkii")
File.WriteAllText(SpeciesPath, sb.ToString)
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
lines = File.ReadAllLines(SpeciesPath)
MessageBox.Show(String.Join(Environment.NewLine, lines))
'OR
MessageBox.Show(File.ReadAllText(SpeciesPath))
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
File.WriteAllLines("C:\Users\maryo\Documents\species2.txt", lines))
End Sub

Importing data from text file in VB.NET

So, I am trying to develop a book database. I have created a table with 11 columns which populates a DGV, where only 6 columns are showed. The full data of each book is shown in a lower part of the form, where I have textboxes, which are bounded (BindingSource) to the table, that change as I move in the DGV.
Now, what I want to do is to have the posibility to export/import data from a file.
I have accomplished the exporting part with the following code:
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
Dim txt As String = String.Empty
For Each row As DataGridViewRow In DbdocsDataGridView.Rows
For Each cell As DataGridViewCell In row.Cells
'Add the Data rows.
txt += CStr(cell.Value & ","c)
Next
'Add new line.
txt += vbCr & vbLf
Next
Dim folderPath As String = "C:\CSV\"
File.WriteAllText(folderPath & "DataGridViewExport.txt", txt)
End Sub
However, I can't manage to import from the txt. What I've tried is this: https://1bestcsharp.blogspot.com/2018/04/vb.net-import-txt-file-text-to-datagridview.html
It works perfectly if you code the table and it populates de DGV without problem. I can't see how should I adapt that code to my need.
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
DbdocsDataGridView.DataSource = table
Dim filas() As String
Dim valores() As String
filas = File.ReadAllLines("C:\CSV\DataGridViewExport.txt")
For i As Integer = 0 To filas.Length - 1 Step +1
valores = filas(i).ToString().Split(",")
Dim row(valores.Length - 1) As String
For j As Integer = 0 To valores.Length - 1 Step +1
row(j) = valores(j).Trim()
Next j
table.Rows.Add(row)
Next i
End Sub
That is what I've tried so far, but I always have an exception arising.
Thanks in advance to anyone who can give me an insight about this.
The DataTable class has built-in methods to load/save data from/to XML called ReadXml and WriteXml. Take a look at example which uses the overload to preserve the schema:
Private ReadOnly dataGridViewExportPath As String = IO.Path.Combine("C:\", "CSV", "DataGridViewExport.txt")
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
table.WriteXml(path, XmlWriteMode.WriteSchema)
End Sub
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
table.ReadXml(path)
End Sub
While users can manually edit the XML file that is generated from WriteXML, I would certainly not suggest it.
This is code which writes to a text file:
speichern means to save.
Note that I use a # in my example for formatting reasons. When reading in again, you can find the # and then you know that and that line is coming...
And I used Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE") to format the Date into German format, but you can decide yourself if you want that. 🙂
Note that I'm using a FileDialog that I downloaded from Visual Studio's own NuGet package manager.
Private Sub Button_speichern_Click(sender As Object, e As EventArgs) Handles Button_speichern.Click
speichern()
End Sub
Private Sub speichern()
'-------------------------------------------------------------------------------------------------------------
' User can choose where to save the text file and the program will save it .
'-------------------------------------------------------------------------------------------------------------
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "store data in a text file"
SFD1.Filters.Add(New CommonFileDialogFilter("Textdatei", ".txt"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName & ".txt"
Else
Return
End If
End Using
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True, System.Text.Encoding.UTF8)
textfile.WriteLine("Timestamp of this file [dd.mm.yyyy hh:mm:ss]: " & Date.Now.ToString("G", Deu) & NewLine & NewLine) 'supposed to be line break + 2 blank lines :-)
textfile.WriteLine("your text")
textfile.WriteLine("#") 'Marker
textfile.Close()
End Using
End Sub
Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
speichern()
End Sub
And this is to read from a text file:
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Pfad, System.Text.Encoding.UTF8)
If RAT.Length = 0 Then Return Nothing
For i As Integer = 0 To RAT.Length - 1 Step 1
If RAT(i) = "#" OrElse RAT(i) = "" Then Continue For
'do your work here with (RAT(i))
Next

Print-to-screen log window

I have to run a process - through the execution of a batch script - which produces an output that is saved as a text file. Furthermore, I need to see this output on a form of the application of mine and, to do this, I've set an iterative timer which updates every second the content of a non-editable RichTextBox but I have two issues:
Each time the timer stops and restarts, I need to create a copy the output file, since the file is used from another process and can't be loaded onto the software as it is;
Creating and loading this text file may be honerous in terms of hardware capability, since this file may reach really big size (even more than 5 GB).
Here is the code I'm providing:
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
[...]
Me.Timer1.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Application.DoEvents()
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.Refresh()
My.Computer.FileSystem.CopyFile(Form1.TextBox5.Text + "/HTAoutput.dat", Form1.TextBox5.Text + "/HTAoutemp.dat", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
RichTextBox1.LoadFile(Form1.TextBox5.Text + "/HTAoutemp.dat", RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Else
Call Button3_Click(sender, e)
End If
End If
End Sub
Is there a more efficient way to show this stream-writing onto my log-window?
Thanks all are gonna answer me
EDIT 1:
Here is the code I'm providing:
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim str As FileStream
str = File.Open(Form1.TextBox5.Text + "/HTAoutput.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.LoadFile(str, RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Application.DoEvents()
Else
Call Button3_Click(sender, e)
End If
End If
Here is a simple demonstration of opening a file once and continuing to read only new data as it is added to that file.
Create a new WinForms Application project with two forms. Add a TextBox and a Button to each form. Make the TextBox multiline on Form1. Add a text file to your project named Test.txt and set Copy to Output Directory to Copy always. Add some default text to the file. Add this code to Form1:
Imports System.IO
Public Class Form1
Private reader As StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Open the file for reading and allow sharing.
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
Dim strm = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
reader = New StreamReader(strm)
'Read all available text and append to the existing text.
TextBox1.Text = reader.ReadToEnd()
Form2.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Read all available text and append to the existing text.
TextBox1.AppendText(reader.ReadToEnd())
End Sub
End Class
and add this code to Form2:
Imports System.IO
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
'Write a new line of text to the file.
File.AppendAllText(filePath, Environment.NewLine & TextBox1.Text)
'Get ready for the next line of text.
TextBox1.Clear()
TextBox1.Select()
End Sub
End Class
Run the project and you'll see your default text in Form1. Enter some text into Form2 and click the Button. Do that a few times. Now click the Button on Form1. Voila! Repeat that cycle and see the text you enter on one form magically appear on the other.
Now go back and examine the code more closely. You can see that Form2 appends a line of code to the file each time you click the Button. Form1 reads the initial contents of the file when it loads and displays that, but it keeps the file open. Each time you click the Button, it will read only the new data, i.e. only the data after where it previously read up to. It then appends that new text to the existing text in the TextBox.

Not read text file correct

I want when I read txt file and add in ListBox1.items, add this text http://prntscr.com/on12e0 correct text §eUltra §8[§716x§8].zip not like this http://prntscr.com/on11kv
My code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
My.Computer.FileSystem.CopyFile(
appDataFolder & "\.minecraft\logs\latest.log",
appDataFolder & "\.minecraft\logs\latestc.log")
Using reader As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\logs\latestc.log")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(" Reloading ResourceManager: Default,") Then
Dim lastpart As String = line.Substring(line.LastIndexOf(", ") + 1)
ListBox1.Items.Add(lastpart)
End If
End While
End Using
My.Computer.FileSystem.DeleteFile(appDataFolder & "\.minecraft\logs\latestc.log")
End Sub
This question is only different from your first question in that your have substituted a ListBox for a RichTextBox. It seems you got perfectly acceptable answers to your first question. But I will try again.
First get the path to the file. I don't know why you are copying the file so I didn't.
Add Imports System.IO to the top of your file. The you can use the File class methods. File.ReadAllLines returns an array of strings.
Next use Linq to get the items you want. Don't update the user interface on each iteration of a loop. The invisible Linq loop just adds the items to an array. Then you can update the UI once with .AddRange.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\.minecraft\logs\latest.log")
Dim lines = File.ReadAllLines(appDataFolder)
Dim lstItems = (From l In lines
Where l.Contains(" Reloading ResourceManager: Default,")
Select l.Substring(l.LastIndexOf(", ") + 1)).ToArray
ListBox1.Items.AddRange(lstItems)
End Sub
If this answer and the previous 2 answer you got don't work, please lets us know why.

Separate String Lines using StreamReader | VB.net

I am trying to make my own checklist app. I am using a ListView object to display each checklist item. I can add individual items to the object. I don't know how to save the ListView items on exit and then load them in on startup. (I tried using My.Settings, but it doesn't work.)
My solution was to make an import/export system using .txt files to store data. They are formatted like this:
Item1
Item2
Item3
When I import them, it all shows as one long item in ListView. I am using the code below.
Private Sub ChooseFileButton_Click(sender As Object, e As EventArgs) Handles ChooseFileButton.Click
If ImportFileDialog.ShowDialog = DialogResult.OK Then
Dim fileReader As String
fileReader =
My.Computer.FileSystem.ReadAllText(ImportFileDialog.FileName)
ImportFileDialog.RestoreDirectory = True
ChecklistObject.Items.Add(fileReader)
End If
End Sub
If anyone knows how to write individual items on their own line in a text file, that would be great too.
EDIT: Exporting doesn't work either. Using code below:
Private Sub ExportButton_Click(sender As Object, e As EventArgs) Handles ExportButton.Click
ExportFileDialog.Filter = "Keklist Save|*.kek"
If ExportFileDialog.ShowDialog = DialogResult.OK _
Then
ChecklistObject.Items.Item()
End If
End Sub
In your example code you are only adding one item to the list view so it will only show the one line.
You could use System.IO.File.ReadAllLines to read all the lines of the file into a string array.
Private Sub ChooseFileButton_Click(sender As Object, e As EventArgs) Handles ChooseFileButton.Click
If ImportFileDialog.ShowDialog = DialogResult.OK Then
Dim path As String = ImportFileDialog.FileName
Dim lines() As String = File.ReadAllLines(path)
ImportFileDialog.RestoreDirectory = True
For Each line in lines
ChecklistObject.Items.Add(line)
Next
End If
End Sub