I have a VB.net program that I have reading a text file, what is the best way to put the text file into VB to be able to check if a string is on one of the lines in a text file, sample code would be helpful.
+2
A:
Dim fileText as string = My.Computer.FileSystem.ReadAllText("c:\AnyFile.txt")
And to check whether a specific line is present in the string, use the Contains
method :)
Ranhiru Cooray
2010-09-03 17:54:31
Bubby4j
2010-09-03 19:59:21
Not sure why you'd use the `My.Computer.FileSystem.ReadAllText()` method rather than `System.IO.File.ReadAllText()`. Seems unnecessarily VB-lockin-ified.
mattmc3
2010-09-03 20:08:42
A:
It might be easier to read the file as an array of strings rather then one lump string, if your doing alot of per line comparisions.
See the MSDN reference to the System.IO.File class.
http://msdn.microsoft.com/en-us/library/3saad2h5.aspx
System.IO.File.ReadAllLines
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
Dim fileLines() as string = System.IO.File.ReadAllLines("c:\AnyFile.txt")
Edit - woops, updated link
asawyer
2010-09-03 18:01:11
How would I search this? If it works better then the other one, I'll choose this answer.
Bubby4j
2010-09-03 20:30:34
for each line as string in fileLines if line="somestring" then messagbox.show("got one!") end ifend for
asawyer
2010-09-03 20:44:54
what exactly are you trying to find out of the text? if it's something simple a bit of linq will do the trick maybe, like:dim foundStrings = from line in fileLines where line = "somestring" select linefor each matchString in foundStrings 'at this point everything in the loop is guanteed to be a match do_something_thing_usefull(matchString)end
asawyer
2010-09-03 20:48:41