views:

28

answers:

2

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 :)

Contains method on MSDN

Ranhiru Cooray
Bubby4j
Not sure why you'd use the `My.Computer.FileSystem.ReadAllText()` method rather than `System.IO.File.ReadAllText()`. Seems unnecessarily VB-lockin-ified.
mattmc3
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
How would I search this? If it works better then the other one, I'll choose this answer.
Bubby4j
for each line as string in fileLines if line="somestring" then messagbox.show("got one!") end ifend for
asawyer
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
Erm, i just want a function that returns true/false if it's in there.
Bubby4j