Replacing strings in multiple text files using regular expressions on vb.net - 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 :)

Related

Getting variables form text file, then setting a new variable

I'm creating a code for the computers at work. I had to make an "Install" program. I didn't know how to do it properly but I found a way to do it.
When I "Install" the program on a other computer I have my USB-stick and copy it to the local disk at the computer.
Now I start the program for the first time at their computer and this code run's
and then I got an error here because Program is not yet divined:
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim Pathproj As String = AppDomain.CurrentDomain.BaseDirectory
Dim Pathfile As String = Pathproj.Replace("bin\Debug\", "Bestanden\Locatie.txt")
Dim Program As String = System.IO.File.ReadAllText(Pathfile)
'Deze bestanden worden aangemaakt en er wordt automatisch een route ingezet.
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim lBibliotheek As String = System.IO.File.ReadAllText(Program & "Bibliotheek.txt")
Dim lExcel_autonummering As String = System.IO.File.ReadAllText(Program & "Excelbestand autonummering.txt")
Dim lLocatie_telbestanden As String = System.IO.File.ReadAllText(Program & "Locatie telbestanden.txt")
Dim lMapnamen As String = System.IO.File.ReadAllText(Program & "Mapnamen.txt")
Dim lOrderschijf As String = System.IO.File.ReadAllText(Program & "Zoek schijf.txt")
Because when the form2_load I do this and then I wan't to divine that string.
Public Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Locatie_05Kuipers As String
If System.IO.File.ReadAllText(Pathfile) = "" Then
'If System.IO.File.ReadAllText("C:\testing1\testing2\testing7\testing1\testing1\text.txt") = "" Then
Locatie_05Kuipers = InputBox("Vul hier de Locatie waar je start bestanden moeten staan. Bijvoorbeeld: K:\Inventor\Instalprogram\ ")
If System.IO.File.Exists(Pathfile) Then
System.IO.File.Delete(Pathfile)
End If
Dim objStreamWriter As StreamWriter
objStreamWriter = New StreamWriter(Pathfile)
objStreamWriter.WriteLine(Locatie_05Kuipers & "\03 - Locaties")
objStreamWriter.Close()
ButtonInstal.Visible = True
Exit Sub
Else
End If
So how or where do I need to put my strings?
You can save a path in your settings, and every time you need it, you can create the file and put your data in it.
For example:
Dim pathString As String = My.Settings.filePath
Dim fullPath = Path.Combine(pathString, "Locatie.txt")
If Not Directory.Exists(pathString) Then
Directory.CreateDirectory(pathString)
File.Create(fullPath)
Else
If Not File.Exists(pathString) Then
File.Create(fullPath)
Else
Console.WriteLine($"File {fullPath}already exists.")
End If
End If

Picking out 1 specific string from a file

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.

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

How do I copy a file that contains the same string as the directory?

I currently have these directories:
C:\testfolder\100
C:\testfolder\101
C:\testfolder\102
and I have these files in the same directory:
C:\testfolder\file-100.txt
C:\testfolder\file-101.txt
C:\testfolder\file-102.txt
What I was trying to do in VB is move text file file-100.txt to the 100 directory. Same for text file file-101.txt, move it to its pertaining folder 101.
My question is how can I write a loop so that my program matches part of the string of my text file name and move it to the matching folder name? Moving one file at a time wouldn't be effecient since I have hundreds of directories and files to apply this to.
Edit:
I'm somewhat familiar with VB. I was having trouble with the logical part of this, in which I couldn't think of a way to write a loop so that it can transfer the files for me.
Without error checking, this would be a simple routine to move those files. It's based on your file names being consistent:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim homePath As String = "c:\testfolder"
Dim files() As String = Directory.GetFiles(homePath, "*.txt")
For Each f As String In files
Dim fileName As String = Path.GetFileName(f)
Dim destPath As String = Path.GetFileNameWithoutExtension(fileName)
destPath = destPath.Split("-")(1)
destPath = Path.Combine(homePath, destPath)
Dim destFile As String = Path.Combine(destPath, fileName)
File.Move(f, destFile)
Next
End Sub
This just gets the list of text files in your directory, parses the file name to get just the number value (100, 101, etc), and then reconstructs the new path. It assumes the directories exist, too.
You can use regular expression to find matched pattern
Dim dir As String = "C:\testfolder\"
Dim fileList() As String = {"C:\testfolder\file-100.txt", _
"C:\testfolder\file-101.txt", _
"C:\testfolder\file-102.txt"}
Dim pattern As New Regex(Replace(dir, "\", "\\") & "file-([0-9]+)[.]txt")
For Each value As String In fileList
Dim match As Match = pattern.Match(value)
If match.Success Then
MsgBox("move from " & dir & " to " & dir & match.Groups(1).Value)
End If
Next
Make sure you have import RegularExpressions.
Imports System.Text.RegularExpressions
Private Sub organizeFiles(ByVal folderPath As String)
For Each filePath As String In Directory.GetFiles(folderPath, "*.txt")
Dim destinationFilePath As String = getDestinationFilePath(filePath)
If destinationFilePath IsNot Nothing Then
File.Move(filePath, destinationFilePath)
End If
Next
End Sub
Private Function getDestinationFilePath(ByVal filePath As String) As String
Const fileNamePrefix As String = "file-"
Dim fileName As String = Path.GetFileName(filePath)
Dim fileNameWithoutExtension As String = Path.GetFileNameWithoutExtension(filePath)
If Not fileNameWithoutExtension.StartsWith(fileNamePrefix) Then
Return Nothing
End If
Dim folderName As String = fileNameWithoutExtension.Substring(fileNamePrefix.Length)
Dim fileFolderPath As String = Path.GetDirectoryName(filePath)
Dim destinationFolderPath As String = Path.Combine(fileFolderPath, folderName)
Dim destinationFilePath As String = Path.Combine(destinationFolderPath, fileName)
Return destinationFilePath
End Function