Question Read a file into an integer array

Pirahnaplant

Well-known member
Joined
Mar 29, 2009
Messages
75
Programming Experience
3-5
How can I convert a file to an integer array? I have been using this method but I'm hoping there is an easier way:
VB.NET:
Dim StreamRead As New System.IO.StreamReader(FileName)
Dim file() As Integer
Dim loops As Integer = -1
While Not StreamRead.EndOfStream
     loops += 1
     Redim Preserve file(loops)
     file(loops) = StreamRead.Read
End While
 
Last edited:
Mind clarifying what you're trying to do here? Find the length of a file (in characters?, bytes?) Take a file that only has integers in it an assign it to an array?

Best guess at what you want:

VB.NET:
		Dim sr As New StreamReader("C:\Temp\Integers.txt")
		Dim fileContents As String = sr.ReadToEnd()

		Dim arr(fileContents.Length - 1) As Integer
		For i As Integer = 0 To fileContents.Length - 1
			arr(i) = CInt(fileContents.Substring(i, 1))
		Next
 
Here's an example where I'm adding each item to a List(Of Integer). If you need to have an array rather than a list then you can call ToArray as shown.

VB.NET:
		Dim intList As New List(Of Integer)

		Using reader As New BinaryReader(File.OpenRead("C:\Temp\BinaryIntegers.dat"))
			Do Until reader.PeekChar() = -1
				intList.Add(reader.ReadInt32)
			Loop
		End Using

		Dim intArr() As Integer = intList.ToArray()
 
Last edited:
There is no BinaryReader type in VS 2008. Do you know of another way to do it?
Edit:Nevermind, its under System.IO
 
Last edited:
Back
Top