object reference error when accessing array

dmarkow

Newcomer
Joined
Feb 18, 2003
Messages
4
I have the following code giving me an error:

Code:
dim myStringArr(2) as String
FileOpen(1,"C:\File1.txt",OpenMode.Input,OpenAccess.Read,OpenShare.Default)
FileOpen(3,"C:\Result.txt",OpenMode.Output,OpenAccess.Write,OpenShare.Default)

myStringArr = LineInput(1).Split(",")
WriteLine(3,myStringArr(0))

myStringArr = LineInput(1).Split(",")
WriteLine(3,myStringArr(0))

It'll perform the first WriteLine fine, but after that, it crashes when trying to perform the second WriteLine. I get an "Object reference not set to an instance of an object."

Any ideas?
 
I believe it's caused by your string (used to get the Split results) being
declared with a subscript already in place.

Also,
Don't use FileOpen! It is a bad method of doing things, left from VB6.
You should always use the StreamWriter/Reader classes;

Try this:
Visual Basic:
        Dim sw As IO.StreamWriter, sr As IO.StreamReader
        Dim myStringArr() As String

        sw = New IO.StreamWriter(New IO.FileStream("C:\Result.txt", IO.FileMode.OpenOrCreate))
        sr = New IO.StreamReader(New IO.FileStream("C:\file1.txt", IO.FileMode.Open))

        Dim tmp As String = sr.ReadLine()
        myStringArr = tmp.Split(",")
        sw.WriteLine(myStringArr(0))

        tmp = sr.ReadLine()
        myStringArr = tmp.Split(",")
        sw.WriteLine(myStringArr(0))

        sr.Close()
        sw.Close()
 
Back
Top