Reputation: 101
Thank you for taking the time to read this question. My question is about VB.NET and converting a text file to a 1D array.
My text file will contain 30 names of technology companies. I want the data values read from TECHNOLOGY into a 1D array called 'companies'. I then want all the companies output with each on a new line.
Please let me know how I can improve my code / correct it fully. Thanks!
Dim sr As New Streamreader("Companies")
Dim words as string=""
Dim company(30) as string
Dim I as Integer=0
Do Until sr.Peek=1
Word=sr.Readline()
company(i)=word
Lstwords.Items.Add(words(i))
i=i+1
Upvotes: 0
Views: 378
Reputation: 4796
If you want to improve this code :
Dim sr As New Streamreader("Companies")
Dim word As String = "" 'To remember the current word
Dim company(30) as string 'The list of companies
Dim i as Integer = 0 'a counter
Word = sr.Readline() 'We read the first line
While Not IsNothing(Word) 'While we read a line (See EDIT for explanation)
Company(i) = word 'We add the word
Lstwords.Items.Add(word) 'I suppose this is a list that you want to display
i += 1 'Increment the counter
Word = sr.ReadLine() 'Read the next line
End While 'End of the loop
EDIT : Why use Not IsNothing(Word)
If you look at the ReadLine() documentation, you find out that when the end of file is reached, that function will return Nothing.
So this is a necessary and sufficient way to know we are not at the end of the file.
Upvotes: 0
Reputation: 1769
You can accomplish this by using File.ReadAllLines
'Load each line of the file into an element of a string array
Dim companies() as string = System.IO.File.ReadAllLines("Companies")
For each company as string in companies
Console.WriteLine(company)
next
Upvotes: 1
Reputation: 1495
I'm not sure what you mean at the end by "output each on a new line", so I've just done it in the console.
Dim companies(29) As String
Dim i As Integer = 0
Dim sr As IO.StreamReader
Dim filename As String
filename = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "companies.txt")
If IO.File.Exists(filename) Then
sr = IO.File.OpenText(filename)
Do While sr.Peek <> -1
companies(i) = sr.ReadLine
i += 1
Loop
sr.Close()
Else
Console.WriteLine("File not found")
End If
For Each company As String In companies
Console.WriteLine(company)
Next
Be aware that this code won't work if you don't have exactly 30 lines of companies in the text file. Modify the code above to deal with contingencies.
Upvotes: 0