Using a textbox value for a file name - vb.net

How do you use a textbox value for VB to save some text to? This is what I have so far:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles butUpdate.Click
Dim ECOLID As String
ECOLID = txtID.Text
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("?", True)
file.WriteLine("ECOL Number:")
file.WriteLine(txtID.Text)
file.Close()
End Sub
The txtID text will determine the title however how can I get it to save it as "C:/Order/'txtID'.txt" for example?

A textbox has a property called Name and this is (usually) the same as the variable name that represent the TextBox in your code.
So, if you want to create a file with the same name of your textbox you could write
file = My.Computer.FileSystem.OpenTextFileWriter(txtID.Name & ".txt", True)
However there is a big improvement to make to your code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles butUpdate.Click
Dim ECOLID As String
ECOLID = txtID.Text
Dim fileName = txtID.Name & ".txt"
Using file = My.Computer.FileSystem.OpenTextFileWriter(fileName, True)
file.WriteLine("ECOL Number:")
file.WriteLine(txtID.Text)
End Using
End Sub
In this version the opening of the StreamWriter object is enclosed in a Using Statement. This is fundamental to correctly release the resources to the operating system when you have done to work with your file because the End Using ensures that your file is closed and disposed correctly also in case of exceptions

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.

VB.NET Program is always reading last created textfile

Trying to create a login form,
My coding is currently:
Imports System
Imports System.IO
Public Class frmLogin
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String
Dim files As Integer
Dim filepath As String
Public Structure info
Dim U As String
Dim P As String
End Structure
Dim details As info
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If txtusername.Text = details.U And txtpassword.Text = details.P Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
End Sub
Private Sub btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
files = files + 1
filepath = "C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt"
Dim di As DirectoryInfo = New DirectoryInfo("C:\Users\TheGlove\Desktop\Alex's Program")
folderpath = "C:\Users\TheGlove\Desktop\Alex's Program"
files = System.IO.Directory.GetFiles(folderpath, "*.txt").Count
For Each fi In di.GetFiles()
MsgBox(fi.Name)
Dim FILE = System.IO.File.ReadAllLines("C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt")
Dim myArray As String() = FILE
details.U = myArray(0)
details.P = myArray(1)
Next
End Sub
End Class
Button 1 will be merged with btnlogin when i get it working and for now is currently just a seperate button to read each textfile.
When each button is pressed (Button 1 -> btnlogin), only the last created textfile is correct.
By the looks of things, your code does read all the text files, but keeps overwriting details.u and details.p with the value retrieved from each file. So, when the loop gets to the last file, those values are what ends up in the details object.
I'm assuming that you want to read all the usernames and passwords into a list and check the details in the TextBoxes against that list, so .. Your code should probably be something like the code below (see the code comments for an explanation of some of the differences.
Before we get to the code, can give you a couple of pointers.
Firstly, always try to use names that are meaningful. Defining your structure as Info is not as meaningful as it could be. For example, you would be better calling it UserInfo and rather than use P and U, you would be better using Password and UserName. It may not matter so much right now, but when you start writing larger more complex programs, and have to come back to them in 6 months time to update them, info.P or details.P aren't as informative as the suggested names.
Secondly, as #ajd mentioned. Don't use magic strings. Create one definition at the beginning of your code which can be used throughout. Again it makes maintenance much easier if you only have to change a string once instead of multiple times, and reduces the chance of mistakes.
Finally, several of the variables you have defined aren't used in your code at all. Again, at this level, it isn't a major issue, but with large programs, you could end up with a bigger memory footprint than you want.
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String = "C:\Users\TheGlove\Desktop\Alex's Program"
Dim files As Integer
Dim filepath As String
Public Structure UserInfo
Dim Name As String
Dim Password As String
End Structure
'Change details to a list of info instead of a single instance
Dim userList As New List(Of UserInfo)
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
'Iterate through the list of details, checking each instance against the textboxes
For Each tempUserInfo As UserInfo In userList
If txtusername.Text = tempUserInfo.Name And txtpassword.Text = tempUserInfo.Password Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
'This is here, because after your form has opened an closed, the loop
'that checks usernames and passwords will continue. The line below exits the loop safely
Exit For
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
Next
End Sub
Private Sub Btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'clear the list of user details otherwise, if the files are loaded a second time,
'you'll get the same details added again
userList.Clear()
'This line replaces several lines in your code that searches the folder for files
'marching the search pattern
Dim fileList() As FileInfo = New DirectoryInfo(folderpath).GetFiles("loginfile*.txt")
For Each fi As FileInfo In fileList
MsgBox(fi.Name)
Dim userDetails() As String = System.IO.File.ReadAllLines(fi.FullName)
Dim tempInfo As New UserInfo With {.Name = userDetails(0), .Password = userDetails(1)}
'An expanded version of the above line is
'Dim tempInfo As New info
'tempInfo.U = userDetails(0)
'tempInfo.P = userDetails(1)
userList.Add(tempInfo)
Next
files = fileList.Count
End Sub