How to search a sub-folder for a particular text file - vb.net

I have a folder titled ‘The Arts’ which contains various sub-folders, one of which is titled ‘Music’. This ‘Music’ sub-folder contains various text files in the format:
John Doe.TXT
John Lennon.TXT
Elton John.TXT
Now, on my Form, I have two Textboxes in which the user can enter the names of artists like so;
Textbox1.Text = John
Textbox2.Text = Lennon
What I want to achieve is that on clicking a button on this form, the program searches the ‘The Arts’ parent folder for the ‘Music’ sub-folder and then searches within this music sub-folder for the text file name which exactly matches the artist name concatenated from Textboxes 1 and 2.
If a text file name exactly matches the artist name concatenated from Textboxes 1 and 2, then display a message. If no text file name within the Music sub-folder matches the name concatenated from Textboxes 1 and 2; then display a message that no file is found.
The below code is incomplete and just shows how I specified the main file path. I do not know how to proceed to get the program to do the above.
I am using Visual Basic 2010 Express. Thank you for your help.
Dim FilePath As String
FilePath = (Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "The Arts\"))
'This section is where I am stuck and need help...Thank you in advance.
If File.Exists(FilePath) Then
MsgBox("File found.")
Else
MsgBox("A record does not exist for this artist.")
Exit Sub
End If

How to check if a text file name exactly matches the artist name concatenated from Textboxes 1 and 2
You need to first concatenate the text from the text boxes, that given your example, need to be separated by a space. There are a few ways to accomplish that.
For example like this:
Dim artistName = TextBox1.Text + " " + TextBox2.Text
Or this:
Dim artistName = String.Concat(TextBox1.Text, " ", TextBox2.Text)
And there are even more ways to do this.
Next you will need to assemble this into a full file path name. For readability it makes sense to do this in a few steps:
' Directory
Dim desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim musicPath = Path.Combine(deskTopPath, "The Arts", "Music"))
' Combine directory name and the name of the file we want to find.
Dim filePath = Path.Combine(musicPath, artistName + ".TXT")
Finally you can check whether that file exists by calling the File.Exists method.
Dim found = File.Exists(filePath)

Related

Find text from folder/subfolder

I had been searching all night for a example how to do this but without luck, only option I found was search in folders.
What I want to try:
I want to search for a word , inside a folder(that includes subfolders too).
1 textbox- where to write what i want to search.
1 textbox2 - where I select extension files what to search only (example I want to search files with *I200.txt that includes in names, so I write in textbox2 "I202.txt".
1 listbox - where to display the results, on what line it found the word (to preview show like notepad shows) and if I double click the results to open the file with notepad.exe.
1 textbox3 - Replace Text (if listview item is selected, the file I want to edit then replace the word with the textbox3 and save file)
I'm really sorry i couldn't find any solution on internet and I'm beginner so if someone wants to help me would appreciate it. Thank you in advance.
Here is what i try now:
Try
'Dim docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim files = From file In Directory.EnumerateFiles("\archives1\library\", "*.txt", SearchOption.AllDirectories)
From line In file.ReadLines(file) Where line.Contains("Microsoft") Select New With {file, line}
For Each f In files
Console.WriteLine($"{f.File} {f.Line}")
Next
Console.WriteLine($"{files.Count.ToString} files found.")
Catch uAEx As UnauthorizedAccessException
Console.WriteLine(uAEx.Message)
Catch pathEx As PathTooLongException
Console.WriteLine(pathEx.Message)
End Try
but i got underline for "file.ReadLines(file)" -Readlines is not a member of String
and the other is For Each f In files -> underline for "files"

How to Auto Copy text file from one folder to another folder in vb 2010 console or windows application

I want to create a program that auto copy text file from one folder to another folder . is it possible to make in windows form in vb.net ? if not what about in console apps ? i tried to search but i didn't find an answer for both. please help me i'm new to to this. I want to copy all the text file that is being save to c:folder1\test1.text copy to c:folder2\test1.text then test2.text,test3.text all the text file that are being put in folder1. i want to copy in folder2.
now i only have this code:
it will only copy 1 specific textfile with file name test.txt.
enter code here
My.Computer.FileSystem.CopyFile("C:\CopyTo\test.txt",
"C:\CopyHere\test.txt")
Of course! First of all we need a function that search for files.
Public Sub SearchFiles(ByVal Pattern As String, ByVal Path As String, ByVal FilesFound As ArrayList)
FilesFound.AddRange(Directory.GetFiles(Path, Pattern))
End Sub
But where we should save the list of files? We can use a Array for it. Also we should define our output and input folder
Dim files As New ArrayList
Dim inDir As String = "input path"
Dim outDir As String = "output path"
We can now call this function like this:
SearchFiles("*.txt", inDir, files)
All .txt files in the folder are now saved in our Array List. But how we can work with it? We can now work with it like this:
Try
For Each file As String In files
Dim fName As String = Path.GetFileName(file)
My.Computer.FileSystem.CopyFile(file , outDir & "\" & fName, overwrite:=False)
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
This will copy every .txt file that where found in our inDir to our outDir. If something goes wrong then you will see this in the console. Try it out and understand how it works :)

How do you retrieve the file path from a checked list box that has multiple subfiles from different directories?

I've got a checked list box that populates files and subfiles from a selected location using a folder browser dialog. What I'm trying to accomplish is retrieve each location/directory of every checked item within that list. I'm using these locations as a spot to copy and paste new files into if that makes sense.
I should add that I'm new to coding, and I don't know how to do something as "complex" as this. This is also my first post and I apologize if this is an easier type question for you guys.
For Each file As IO.FileInfo In ListBox1.CheckedItems
Dim NewFileName As String = FindListBox2ItemThatContains(file.Name)
Dim lstfiles As String = Directory.GetFiles(FBD2.SelectedPath)
If NewFileName.Trim.Length > 0 Then
IO.File.Copy(file.FullName, IO.Path.Combine(FBD2.SelectedPath, "item parent folder", NewFileName.Trim), True)
End If
ProgressBar1.Increment(+1)
Next

How do I search multiple textfiles for text, then adding that text into a listbox

I've got multiple text files within a folder, like this:
C:\Example\ 1.txt, 2.txt, 3.txt, 4.txt
The file names are generated by time and date they were created at so please don't try to open/search the documents using [1-4].txt or something similar as these are just examples.
I would like to search through all of these text files (without knowing their names as they're randomly generated), and if it matches certain text, I would like the rest of the text on that line to be added into a ListBox, then search the next/rest of the text files.
Example of text file contents:
[14:49:16] [Client thread/INFO]: Setting user: Users Name
All text after Setting user: which is on the same line should be added to the ListBox, so in this case, Users Name would be added.
The above text will always be the first line of the text file, so no need to search the whole file, the beginning of the text will always be the time created at (which will be different for each text file), then followed by [Client thread/INFO]: Setting user: which will always be the same for all of the text files, then Users Name , which wont actually output Users Name, this is what I would like to find, and then add to the ListBox.
I've got some of the code created, but there's three problems with it.
1: I have to define the name of the text file, which I will not know.
2: I'm not sure how to search through all of the documents, only the one that is defined.
3: I can get it to output the Users name, but only if I remove the leading time and [Client thread/INFO]:, but these items will always be there.
With these three problems, the code is useless, I'm just providing it as possibly it will make it easier for someone to help me?
Public Class Form1
Private Sub LoadFiles()
For Each line As String In IO.File.ReadLines("C:\Example\2016-09-28-1.txt")
'I had to define the name of the text file here, but I need to somehow automatically
'search all .txt files in that folder.
Dim params() As String = Split(line, ": ")
Select Case params(0)
'Text file has to be modified to show as:
Setting user: RandomNameHere
'for the RandomName to show within the ListBox,
'but normally it will never be shown like this within the text files.
Case "Setting user"
ListBox1.Items.Add(params(1))
End Select
Next
End Sub
Use System.IO.Directory.GetFiles to get the list of files, and System.IO.Path.GetExtension to filter for .txt files. The String.IndexOf function will let you search for text within each line of the file, and String.Substring will let you retrieve part of the line.
While your original code using Split could be made to work (you would need another loop to go through the split text), I think IndexOf and Substring are simpler in this case.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strFilenames() As String = System.IO.Directory.GetFiles("C:\Example")
For i As Integer = 0 To strFilenames.GetUpperBound(0)
Dim strFilename As String = strFilenames(i)
If System.IO.Path.GetExtension(strFilename).ToLower = ".txt" Then
For Each strLine As String In System.IO.File.ReadLines(strFilename)
'[14:49:16] [Client thread/INFO]: Setting user: Users Name
Dim strSearchText As String = "Setting user: "
Dim intPos As Integer = strLine.IndexOf(strSearchText)
If intPos > -1 Then
Dim strUsername As String = strLine.Substring(intPos + strSearchText.Length)
MsgBox(strFilename & " - " & strUsername) '<-- replace this with your SELECT CASE or whatever
End If
Next strLine
End If
Next i
End Sub
You can use system.io.directory class and use the getfiles method to get the filenames from a directoy. then you can open the file and do the needful.
https://msdn.microsoft.com/en-us/library/system.io.directory.getfiles(v=vs.110).aspx

VB.net String Extraction

At the company I work at, I have a software that I am developing in vb.net. This software uses a web browser control to load an excel file that the employee can modify. If then saves a copy of the excel file as an excel file for future modification, it saves it as a pdf file, to send to the customer, then prints the first page twice. I am trying to create a quote list. Quote File names are structured as follows...
12345 My Company Name Here 10-25-2013.pdf
Is there any way to "extract" just the "My Company Name Here" in the above example. I tried removing all numbers, and then the - and .pdf from the string, but it actually makes it where fewer results appear in the list view control. Any Ideas?
Dim di As New IO.DirectoryInfo("Z:\Quotes\" & Today.Year & "\" & Today.Month _
& " " & MonthName(Today.Month))
Dim diar1 As IO.FileInfo() = di.GetFiles("*.pdf")
Dim dra As IO.FileInfo
ListView1.View = View.Details
ListView1.Columns.Clear()
ListView1.Columns.Add("Quote Number")
ListView1.Columns.Add("Customer Name")
ListView1.Columns(0).Width = -2
ListView1.Columns(1).Width = -2
For Each dra In diar1
If dra.ToString.Contains("Product") = False Or dra.ToString.Contains("Thumbs.db") Then
Dim newIrm() = dra.ToString.Split(" ")
Dim NumericCharacters As New System.Text.RegularExpressions.Regex("\d")
Dim nonNumericOnlyString As String = NumericCharacters.Replace(newIrm(2), String.Empty)
ListView1.Items.Add(New ListViewItem({newIrm(0), newIrm(1) & newIrm(2)}))
End If
Next
Filename Format:
Z:\Quotes\2013\10 October\12345-RR My Company Name Here 10-25-2013.pdf
By assuming that the company name is always surrounded by blank spaces and that all the surrounding text does not contain any, you can use IndexOf and LastIndexOf. Sample code:
Dim input As String = "Z:\Quotes\2013\10 October\12345-RR My Company Name Here 10-25-2013.pdf"
Dim companyName As String = System.IO.Path.GetFileNameWithoutExtension(input)
companyName = companyName.Substring(companyName.IndexOf(" "), companyName.LastIndexOf(" ") - companyName.IndexOf(" ")).Trim()
If these conditions do not fully apply, you would have to describe clearly the constraints in order to update this code. Without systematically-applied constraints, there wouldn't be any way to deliver an accurate solution for this problem.
The postfix (date.pdf) is a constant size assuming your date format uses leading zeros.
The prefix is a variable size, however the first space of the complete file name always comes before the first character of the company name.
Using these two facts, you can easily find the index of the first and last character of the company "extract" the company name using this information.
Alternatively, you can split the file name into an array using space as your delimiter. You can then grab every index of the array, excluding the first and last index, and combine these elements seperated by a space.