Question Read file and save each line as a seperate variable

Haxaro

Well-known member
Joined
Mar 13, 2009
Messages
105
Programming Experience
1-3
How can i make a program that will read a text file (.txt) and save each seperate line as a variable?

e.g.

Text File:
Hello
My
Name
Is
Haxaro

would be saved in the program as variables as:
A = Hello
B = My
C = Name
D = Is
E = Haxaro

Thanks!
 
VB.NET:
Dim lines() As String = IO.File.ReadAllLines("filepath")
You can also use a StreamReader (System.IO).
 
Thats not exactly what i ment. What i mean is that:

I want to read lines 1, 3 and 5, not all of them, which ReadAllLines does?

I have experimented with ReadLine() but i cant seem to get it to work
 
You have to read all lines (at least up to the last one you want to read), which lines you decide to process is up to you.
 
I need a sample code to open a .txt file, and save each separate line as a variable?

I have been trying to work out a way that i can open a .txt file, and save every separate line as its own string such as:
VB.NET:
Line1 = File.line1
Line2 = File.line2

I really need this code asap, and any suggestions would be greatly appreciated

Thanks!
 
Please post in the forum most appropriate for the topic. Moved.

You can just call IO.File.ReadAllLines to get a String array, or you can create a StreamReader and call ReadLine multiple times.
 
?

Sorry.

Ive been trying similar things for ages.

I dont mean to be a pain, but could you write a quick sample code so i can actually understand?

Thanks,
Haxaro
 
You've obviously been trying the wrong things. Now that you know the right things to try you can do it very quickly and easily. At least try to do what I suggested. If you try and fail then I'm quite prepared to help.
 
Example using File.ReadAllLines and removing the lines you don't need.

VB.NET:
		Dim allLines As New List(Of String)
		allLines.AddRange(File.ReadAllLines("C:\Temp\MyFile.txt"))

		For i As Integer = allLines.Count - 1 To 0 Step -1
			If i Mod 2 <> 0 Then
				allLines.RemoveAt(i)
			End If
		Next

		Dim myArr() As String = allLines.ToArray()

Example using a StreamReader and only adding the lines your interested in.

VB.NET:
		Dim alternateLines As New List(Of String)
		Dim idx As Integer = 0

		Using sr As New StreamReader("C:\Temp\MyFile.txt")
			While sr.Peek <> -1
				If idx Mod 2 = 0 Then
					'Read line and add it to your List
					alternateLines.Add(sr.ReadLine())
					idx += 1
				Else
					'Read line and do nothing with it
					sr.ReadLine()
					idx += 1
				End If
			End While
		End Using

		Dim arr() As String = alternateLines.ToArray()
 
It's just an array like any other, so you access it's elements like any other. You can get a specific element by index or loop through them all using a For Each loop. If you don't know how to work with arrays (which picoflop has already asked and you haven't answered) then you should do some reading about arrays.

Arrays in VB .NET
 
Back
Top