Been a while since I've coded in VB and was wondering whether someone can help me.
I'm making an app where you browse a folder, it then lists all files in that folder which are txt files inside of a listbox1.
This listbox contains the path to each file.
Now I'm wanting to open each file one by one and find a string of text in the file, replace it, write/save it and then move onto the next file in the list.
This is my code at the moment.
Browse folder and list the files inside folder inside the listbox1 as items.
FolderBrowserDialog1.ShowDialog()
ComboBox1.Text = FolderBrowserDialog1.SelectedPath
Try
Dim folderInfo As New IO.DirectoryInfo(ComboBox1.Text)
Dim arrFilesInFolder() As IO.FileInfo
Dim fileInFolder As IO.FileInfo
arrFilesInFolder = folderInfo.GetFiles("*.txt")
For Each fileInFolder In arrFilesInFolder
ListBox1.Items.Add(fileInFolder.FullName)
Next
Catch
End Try
This works fine.
Now here's the tricky bit, I can't work my head around this as I've never had to do such a thing.
Code which edits the text file, moves onto the next and loops through it until it finds a certain string.
So if I had a text files inside of a folder and some contained different information it would stop the loop when it finds that string.
So FILEEXAMPLE1.txt, FILEEXAMPLE2.txt, FILEEXAMPLE4.txt, FILEEXAMPLE5.txt, FILEEXAMPLE6.txt contained this info:
HELLO
MY
NAME
IS
JOE
But FILEEXAMPLE7.txt SAYS:
HELLO
MY
NAME
IS
BOB
It would loop through all of the FILEXAMPLE1-6.txt and replace the string I select, but when gets to FILEEXAMPLE7.txt it will stop the loop.
I'm assuming it's a while loop I need?
Here's my code, my main priority is getting it to write to the file, save it and move down to the next listbox item, and keep going on etc..
Do Until Text.EndsWith("TAG")
Text = File.ReadAllText(ListBox1.SelectedItem)
Text = Text.Replace(TextBox1.Text, TextBox2.Text)
File.WriteAllText(ListBox1.SelectedItem, Text)
ListBox1.Select()
SendKeys.Send("{DOWN}")
System.Threading.Thread.Sleep(100)
Loop
Thank you
I was using this code but got file permission errors:
Try
Dim fso, inputFile, outputFile
Dim str As String
fso = CreateObject("Scripting.FileSystemObject")
inputFile = fso.OpenTextFile(ListBox1.SelectedItem, 1)
str = inputFile.ReadAll
str = Replace(str, TextBox1.Text, TextBox2.Text)
outputFile = fso.CreateTextFile(ListBox1.SelectedItem, True)
outputFile.Write(str)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

New Topic/Question
Reply




MultiQuote




|