VB.NET Program is always reading last created textfile - vb.net

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

Related

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

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.

Using a textbox value for a file name

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

Using a combo box to store items in an array from a text file and then using that array and its components in another form

I'm currently designing an application within visual basic using vb.net. The first form asks for login information and then prompts the next form to select a customer. The customer information is stored in a text file that gets put in an array. I next have a form for the user to display and edit that information. How can I use the array I already created in the previous form in my display and edit form?
Private Sub frmCustomerList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sr As StreamReader = File.OpenText("customer.txt")
Dim strLine As String
Dim customerInfo() As String
Do While sr.Peek <> -1
strLine = sr.ReadLine
customerInfo = strLine.Split("|")
cboCustomers.Items.Add(customerInfo(0))
customerList(count) = strLine
count = count + 1
Loop
End Sub
Private Sub cboCustomers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCustomers.SelectedIndexChanged
Dim customerInfo() As String
Dim index As Integer = cboCustomers.SelectedIndex
Dim selectedCustomer As String = customerList(index)
customerInfo = selectedCustomer.Split("|")
End Sub
Make the next form require it in the constructor:
Public Class EditCustomer
Public Sub New(customerInfo As String())
InitializeComponent() 'This call is required, do not remove
'Yay! Now you have your info
End Sub
End Class
You'd call it by doing something like...
Dim editForm = New EditCustomerFrom(customerInfo)
editForm.Show()
Alternatively, you could have a property on the form you set.
Dim editForm = New EditCustomerFrom()
editForm.Customer = customerInfo
editForm.Show()
Then inside the Load event of that form, you'd write the logic that would display it looking at that property.
Aside: You should look at maybe defining an object to hold customer info and do some JSON or XML serialization for reading/writing to the file, IMO. This architecture is kind of not good as is....

WinNT giving to much information. I need to narrow down to just Machine Names

Dim de As New System.DirectoryServices.DirectoryEntry()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
de.Path = "WinNT://*****".Replace("*****", ActiveDirectory.Domain.GetCurrentDomain.Name)
Dim Mystream As Object
MsgBox("Please choose the place you want the file")
If savefileDialog1.ShowDialog() = DialogResult.OK Then Mystream = savefileDialog1.FileName
Dim UserFile As String = savefileDialog1.FileName & ".txt"
Dim fileExists As Boolean = File.Exists(UserFile)
Using sw As New StreamWriter(File.Open(UserFile, FileMode.OpenOrCreate))
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
End Using
End Sub
I am getting a large number of entries written out to the text file. The bottom half of the file is all that I really need. The bottom half seems to be the list of all machine names on the domain and the first half is filled with names or printers, and other names that i cannot "pushd \" into.
I am unable to figure out what will cut down this user list and give me only the machine names.
You might find something here...look at "Enumerate Objects in an OU"
Public Function EnumerateOU(OuDn As String) As ArrayList
Dim alObjects As New ArrayList()
Try
Dim directoryObject As New DirectoryEntry("LDAP://" + OuDn)
For Each child As DirectoryEntry In directoryObject.Children
Dim childPath As String = child.Path.ToString()
alObjects.Add(childPath.Remove(0, 7))
'remove the LDAP prefix from the path
child.Close()
child.Dispose()
Next
directoryObject.Close()
directoryObject.Dispose()
Catch e As DirectoryServicesCOMException
Console.WriteLine("An Error Occurred: " + e.Message.ToString())
End Try
Return alObjects
End Function
I'm not sure if there is much difference in our active directory setups, but I ran the following code in a console application and it only output the AD Names (as expected):
Module Module1
Sub Main()
Using de As New System.DirectoryServices.DirectoryEntry
de.Path = "WinNT://*****".Replace("*****", System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain.Name)
For Each d As System.DirectoryServices.DirectoryEntry In de.Children()
If d.SchemaEntry.Name = "User" Then
Console.WriteLine(d.Name)
End If
Next
Console.ReadKey()
End Using
End Sub
End Module
EDIT:
Code change to only output members with the SchemaType of "User"