Reputation: 107
A few days ago, I asked a question on Stack Overflow, asking how to search a text file for matching strings from a search text box. This has worked great so far, except from the fact that the search was case sensitive. I thought of a way of overcoming this, however it wouldn't work in the way I necessarily wanted it to.
My idea/solution:
If ListBox.Items.Count = 0 Then
tbx_FindText.CharacterCasing = CharacterCasing.Upper
ElseIf ListBox.Items.Count = 0 Then
tbx_FindText.CharacterCasing = CharacterCasing.Lower
End If
This would essentially try both fully upper and lower case, but what happens if the user types a search request such as 'Gsk', well the 'G' is capitalized, but the other characters aren't (because the string is mixed case, not fully upper or lower case), and if it is not the exact same as the string in the text file (whether it be fully upper or lower case or mixed case, then the program reports that there are no search results, when there are - it's just that the search algorithm used is case sensitive and doesn't recognize/search it properly.
Search Algorithm Code:
Dim lines1() As String = IO.File.ReadAllLines("C:\ProgramData\WPSECHELPER\.data\Outlook Folder Wizard\outlookfolders.txt")
lbx_OFL_Results.Items.Clear()
lbx_OFL_Results.BeginUpdate()
For i As Integer = 0 To lines1.Length - 1
If lines1(i).Contains(tbx_FindText.Text) Then lbx_OFL_Results.Items.Add(lines1(i))
Next
lbx_OFL_Results.EndUpdate()
Essentially, the code opens the text file, which contains several Outlook Folder Paths needed by employees to do their jobs. They enter a search for a company name or reference number into a search box, and the list box populates with matching results of paths that contain the keywords that were entered in the search text box.
That part works great - apart from the fact the list box doesn't populate with results if my search is capitalized, and the string in the text file isn't, for example.
If anyone could help compose (or reconstruct) a piece of code that searches the text file (trying to keep the code above if possible) whilst the search not being case sensitive, it would be greatly appreciated.
Upvotes: 2
Views: 324
Reputation:
Don't use the ReadAllLines
function since you don't need to get all the lines from the text file. This function loads everything in memory which is unnecessary especially when you are dealing with big files. Use ReadLines
instead with the where
extension function to get the matches:
Dim path As String = "C:\ProgramData\WPSECHELPER\.data\Outlook Folder Wizard\outlookfolders.txt"
Dim search As String = tbx_FindText.Text
Dim lines = File.ReadLines(path).Where(
Function(l) l.IndexOf(search, 0, StringComparison.InvariantCultureIgnoreCase) >= 0
).ToList
lbx_OFL_Results.DataSource = Nothing
lbx_OFL_Results.DataSource = lines
Upvotes: 2