Picking out 1 specific string from a file - vb.net

Ive put in multiple strings in 1 line of a file, so that they are linked together, I have tried multiple ways such as using loops and I was wondering if if anyone could help me, thanks.
in file: swagman (username), samfisher34 (password), sam fisher (fullname)
Private Sub btn_login_Click(sender As Object, e As EventArgs) Handles btn_login.Click
Dim Student As New StreamReader("student.txt")
Dim newline As String
Dim login As Boolean
Dim line1 As String
Dim line2 As String
' Reads the files to a string and write the string to the console.
Dim count As Integer = 20
For i = 1 To count
newline = Student.ReadLine
If txt_login.Text = newline And txt_password.Text = newline Then
'Checks to see if text is the same in the Files.
login = True
End If
If login = True Then
Me.Hide()
StudentMenu.Show()
End If
Next
If login = False Then
MsgBox("login or password is incorrect")
End If
Student.Close()
End Sub

Here is a really basic code example that I made:
First of all you need to import System.IO for the StreamReader
Dim objStreamReader As StreamReader
Dim strLine As String
objStreamReader = New StreamReader(File)
Dim splitresult As Array
'read the file line for line
Do Until objStreamReader.Peek = -1
strLine = objStreamReader.ReadLine
'split the results (user,pwd,name)
splitresult = strLine.Split(",")
If splitresult(0) = user Then
If splitresult(1) = pwd Then
MsgBox("Welcome " & splitresult(2))
End If
Loop
Also please don't store your password as plain text.

Related

How to combine all csv files from the same folder into one data

I want merge multiple csv files with same layout from the same folder
example :
csv1.csv
ID, PINA,PINB,PCS
1,100,200,450
2,99,285,300
csv2.csv
ID, PINA,PINB,PCS
1,100,200,999
2,99,285,998
out.csv (The file I want make by VB.net)
ID, PINA,PINB,PCS,PCS
1,100,200,450,999
2,99,285,300,998
my problem code :
Dim FileReader As StreamReader
Dim i As Integer = 0
Dim temp As String
For i = 0 To LstFiles.Items.Count - 1
FileReader = File.OpenText(LstFiles.Items.Item(i))
temp = FileReader.ReadToEnd
File.AppendAllText(SaveFileDialog1.FileName, temp)
Next
Please guide me.
Thanks a lot !
Looks to me like each line in the input files has an identifier based on the first value in that row. You want to combine all the numbers after that identifier, from all the files in your ListBox, into one list of numbers that is sorted and has no duplicates. Then you want to generate an output file that has all those identifiers followed by each set of sorted, unique numbers.
If that is correct, then try this out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
Dim header As String = ""
Dim combinedLines As New SortedList(Of Integer, List(Of Integer))
For Each filename As String In LstFiles.Items
Dim lines = File.ReadLines(filename)
If header = "" Then
header = lines.First
End If
lines = lines.Skip(1)
For Each line As String In lines
Dim strValues = line.Split(",").AsEnumerable
Try
Dim lineNumber As Integer = Integer.Parse(strValues.First)
strValues = strValues.Skip(1)
Dim numbers = strValues.ToList.ConvertAll(Of Integer)(Function(x) Integer.Parse(x))
If Not combinedLines.ContainsKey(lineNumber) Then
combinedLines.Add(lineNumber, New List(Of Integer)(numbers))
Else
combinedLines(lineNumber).AddRange(numbers)
End If
Catch ex As Exception
MessageBox.Show("Error Parsing Line: " & line)
End Try
Next
Next
Using sw As New StreamWriter(SaveFileDialog1.FileName, False)
sw.WriteLine(header)
For Each numberSet In combinedLines
Dim numbers = numberSet.Value.Distinct.ToList
numbers.Sort()
sw.WriteLine(numberSet.Key & "," & String.Join(",", numbers))
Next
End Using
End If
End Sub

Visual Basic: i have a file containg usernames and passwords but i want to read them back in so the user can log back in

Do
Do
Console.WriteLine("Create a password. It must be 8 characters in length")
password1 = Console.ReadLine()
Loop Until password1.Length = 8
Console.WriteLine("Please re-enter the password.")
password2 = Console.ReadLine()
Loop Until password2 = password1
password = password1
Console.WriteLine("your password has been created.")
Console.ReadLine()
The below code generates the file
Dim fileName = "C:\Users\emily\Documents\Details.csv"
Dim fileAppend As New System.IO.StreamWriter(fileName, True)
fileAppend.WriteLine(name & ", " & age & ", " & username & ", " & password & ", " & yeargroup)
fileAppend.Close()
So basically I have details about the users stored in a csv file. The columns are arranged as follows: name, age, username, password, yeargroup. I need to be able to input a username and for it to be found in the array/list and then input the password and if the password doesn't match for it to start again.
Nice homework. You should think about storing password. Clear text is obviously risky. With the user file load in a table like this will let you manage all of the user. Add,Remove, Change then just save over the userfile.
Public Class Form1
Dim UserTable As New DataTable("UserTable")
Dim SomeUserName As String = "slims"
Dim SomePassword As String = "abc1234!"
Sub ReadUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileReader As New System.IO.StreamReader(fileName)
UserTable.Columns.Add("Name")
UserTable.Columns.Add("Age")
UserTable.Columns.Add("Username")
UserTable.Columns.Add("Password")
UserTable.Columns.Add("YearGroup")
Do Until fileReader.EndOfStream = True
Dim OneLine As String = fileReader.ReadLine()
UserTable.Rows.Add(OneLine.Split(","))
Loop
fileReader.Close()
End Sub
Sub WriteUserFile()
Dim fileName = "C:\dump\test.csv"
Dim fileWriter As New System.IO.StreamWriter(fileName)
For Each xRow As DataRow In UserTable.Rows
fileWriter.WriteLine(String.Format("{0},{1},{2},{3},{4}", xRow("Name"), xRow("Age"), xRow("Username"), xRow("Password"), xRow("YearGroup")))
Next
fileWriter.Close()
End Sub
Function CheckUserPassword(UserName As String, Password As String) As Boolean
Dim Found As Boolean = False
For Each xRow As DataRow In UserTable.Rows
If (xRow("Username") = SomeUserName) And (xRow("Password") = SomePassword) Then
Found = True
Exit For
Else
Found = False
End If
Next
Return Found
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadUserFile()
If CheckUserPassword(SomeUserName, SomePassword) = True Then
'Good to go
Else
'bad user/pass
End If
WriteUserFile()
End Sub
End Class
You can use IO.File.ReadAllLines(fileName) to read the lines into an array of strings. Then you can use String.Split() on each line to split the fields and pick out the username and password.
dim allLines as String() = IO.File.ReadAllLines(fileName)
for each line as String in allLines
dim lineArray() as string
lineArray = line.Split(New Char() {","c})
username = lineArray(2)
password = lineArray(3)
if username = theUsernameYouWant then
'Found the user. Now check their password
endif
next
I havn't tested this code. Might have syntax errors.

Replacing strings in multiple text files using regular expressions on vb.net

I'm looking to build a simple text string replacement tool using visual studio 2015 community tool, which will do the below replacements on all *.txt files whose path is given in a textbox:
Find: \<figure (\d+)\>
Replace: <a href id="fig\1">figure \1</a>
Find: \<table (\d+)\>
Replace: <a href id="tab\1">table \1</a>
Find: \<section (\d+)\>
Replace: <a href id="sec\1">section \1</a>
I have coded a little portion of the programme but struggling to complete it. I'm completely new in programming and in visual basic is well. Can anyone help complete this programme
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FBD.ShowDialog = DialogResult.OK Then
TextBox1.Text = FBD.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim targetDirectory As String
targetDirectory = TextBox1.Text
Dim Files As String() = Directory.GetFiles(targetDirectory, "*.txt")
For Each file In Files
Dim FileInfo As New FileInfo(file)
Dim FileLocation As String = FileInfo.FullName
Dim input As String = file.ReadAllLines(FileLocation)
Dim pattern1 As String = "\<figure (\d+)\>"
Dim pattern2 As String = "\<table (\d+)\>"
Dim pattern3 As String = "\<section (\d+)\>"
Dim rep1 As String = "<a href id= \""fig\1\"" > figure \1</a>"
Dim rep2 As String = "<a href id= \""tab\1\"" > table \1</a>"
Dim rep3 As String = "<a href id= \""sec\1\"" > section \1</a>"
Dim rgx1 As New Regex(pattern1)
Dim rgx2 As New Regex(pattern2)
Dim rgx3 As New Regex(pattern3)
Dim result1 As String = rgx1.Replace(input, rep1)
Dim result2 As String = rgx2.Replace(result1, rep2)
Dim result3 As String = rgx3.Replace(result2, rep3)
Next
End Sub
End Class
The errors I'm getting are given below
Error BC30456 'ReadAllLines' is not a member of 'String'
For the replace button, once you have the link to the folder directory, you need to read in all files that say "*.txt". The below line does this
targetDirectory = TextBox1.text
Dim txtFilesArray As String() = Directory.GetFiles(targetDirectory,"*.txt")
You can then loop through this array and do your replace logic.
For each txtFile in txtFilesArray
'here we grab the files information as we need the files directory
Dim FileInfo As New FileInfo(txtFile)
Dim FileLocation As String = FileInfo.FullName
Dim input() as string = File.ReadAllLines(FileLocation)
'now you have read in your text file you can edit each file as it goes through the loop
'you can now use your regex here to edit each file,
'then once done editing the file, dont forget to write back to your file or it wont save
'you will need to loop through the input array now to change the line
For x as integer = 0 to (input.length - 1)
Dim pattern1 As String = "\<figure (\d+)\>"
Dim pattern2 As String = "\<table (\d+)\>"
Dim pattern3 As String = "\<section (\d+)\>"
Dim rep1 As String = "<a href id= \""fig\1\"" > figure \1</a>"
Dim rep2 As String = "<a href id= \""tab\1\"" > table \1</a>"
Dim rep3 As String = "<a href id= \""sec\1\"" > section \1</a>"
Dim rgx1 As New Regex(pattern1)
Dim rgx2 As New Regex(pattern2)
Dim rgx3 As New Regex(pattern3)
Dim result1 As String = rgx1.Replace(input(x), rep1)
Dim result2 As String = rgx2.Replace(result1, rep2)
Dim result3 As String = rgx3.Replace(result2, rep3)
input(x) = result3
Next
'now you can write your corrected file back to the file
File.WriteAllLines(FileLocation, input)
Next
MsgBox("process complete")
#Tamal Banerjee, try this for progress bar, put the below code after the last Next in the coding
Next
ProgressBar1.PerformStep()
ProgressBar1.Value = 100
MessageBox.Show("Process complete")
End Sub
I'm not sure whether this is the write way to do it, but it worked when tried this on my computer with your coding :)

Read random txt line, split strings by : and write in textboxes

I've got two textboxes and I want make account generator which will read random line from txt file on website and write it into textboxes. So, I want to read random line(just one) from a text file, where email and password are separated by : so .txt file would look like email#site.com:password , write data before : in textbox1(email) and write data from the same line after : in textbox2.
.txt file looks like this:
email1#example.com:password1
email2#example.com:password2
email3#example.com:password3 etc....
I cannot figure out how to split this strings, any help will be appreciated, thanks anyway :)
There you go.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
tbxEmail.Text = String.Empty
tbxPassword.Text = String.Empty
Dim lines As String() = getData("URL_OF_FILE")
Dim lineCount As Integer = lines.Length
Dim randomValue As Integer = CInt(Math.Floor((lineCount) * Rnd()))
Dim line As String = lines(randomValue)
Dim parts As String() = line.Split(New Char() {":"c})
Dim email As String = parts(0)
Dim password As String = parts(1)
tbxEmail.Text = email
tbxPassword.Text = password
End Sub
Function getData(url As String) As String()
Dim client As System.Net.WebClient = New System.Net.WebClient()
Dim data As String = client.DownloadString(url)
Dim returnValue As String() = data.Split(New String() {Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries)
Return returnValue
End Function
Please not that this is a synchronous request, meaning it will "freeze" your application for the duration of the request.

Loop through the lines of a text file in VB.NET

I have a text file with some lines of text in it.
I want to loop through each line until an item that I want is found*, then display it on the screen, in the form of a label.
*I am searching for the item through a textbox.
That is, in sudo:
For i = 0 To number of lines in text file
If txtsearch.text = row(i).text Then
lbl1.text = row(i).text
Next i
You can use the File.ReadLines Method in order to iterate throughout your file, one line at a time. Here is a simple example:
Dim Term As String = "Your term"
For Each Line As String In File.ReadLines("Your file path")
If Line.Contains(Term) = True Then
' Do something...Print the line
Exit For
End If
Next
Here's a function that will spit back your string from the row that contains your search term...
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
To use the function you can do this...
Dim strText As String = SearchFile(FileName, SearchTerm)
If strText <> String.Empty Then
Label1.Text = strText
End If
LOOPING AND GETTING ALL XML FILES FROM DIRECTORY IF WE WANT TEXTFILES PUT "*.txt" IN THE PLACE OF "*xml"
Dim Directory As New IO.DirectoryInfo(Path)
Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.xml")
allFiles = allFiles.OrderByDescending(Function(x) x.FullName).ToArray()
Dim singleFile As IO.FileInfo
For Each singleFile In allFiles
'ds.ReadXml(singleFile)
xd.Load(singleFile.FullName)
Dim nodes As XmlNodeList = xd.DocumentElement.SelectNodes("/ORDER/ORDER_HEADER")
Dim ORDER_NO As String = " "
For Each node As XmlNode In nodes
If Not node.SelectSingleNode("ORDER_NO") Is Nothing Then
ORDER_NO = node.SelectSingleNode("ORDER_NO").InnerText
End If
Next
Next