当前位置: 动力学知识库 > 问答 > 编程问答 >

vb.net - Variable has already been used before and assigned a value

问题描述:

I' am making a bot for my assignment which uses proxy to browse websites. I have field called "Browse" which lets me browse for the proxy file and reads into an array and shows the total number of proxy from the counter. I' am stuck here in the following. The following are the code that am currently using. Please help

Variable proxyArray has already been used before and assigned a value. A null

reference exception could result at runtime.

Code

Private Sub browserProxy_Click(sender As Object, e As EventArgs) Handles browserProxy.Click

Dim myStream As Stream = Nothing

Dim selectedFile As String

Dim openFileDialog1 As New OpenFileDialog()

Dim proxyArray() As String

Dim totalProxy As Integer

openFileDialog1.InitialDirectory = "C:\"

openFileDialog1.Filter = "Text File (*.txt)|*.txt"

openFileDialog1.FilterIndex = 1

openFileDialog1.RestoreDirectory = False

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

selectedFile = String.Format(openFileDialog1.FileName)

Dim objreader As New System.IO.StreamReader(selectedFile)

i = 0

Do While Not objreader.EndOfStream

proxyArray(i) = objreader.ReadLine

i += 1

Loop

totalProxy = i

objreader.Close()

End If

End Sub

This pops up during runtime.

网友答案:

The compiler is right, you have declared the variable proxyArray but you never initialize it. This is an initialized array with 10 strings that are Nothing :

Dim proxyArray(9) As String

But since the number of items is unknown you should use a List(Of String) anyway. It is resizable whereas an array has a fixed size.

Dim proxList As New List(Of String)
'...'
     proxList.Add(objreader.ReadLine)

If you need an array you can use proxList.ToArray() at the end.

网友答案:

Either use a List(Of String), or ReDim Preserve proxyArray(i + 1) each time.

分享给朋友:
您可能感兴趣的文章:
随机阅读: