2013-07-04 65 views
0

我得到這個錯誤,當我運行我的程序:對象變量還是有塊變量未設置?

型「System.NullReferenceException」的第一次機會異常出現在Microsoft.VisualBasic.dll中

對象變量或與塊變量未設置

這裏是我的代碼:

Dim rt As String = "" 
    Dim out As String 
    Dim wRequest As WebRequest 
    Dim wResponse As WebResponse 
    Dim SR As StreamReader 
    Dim time As Date 

    time = Now() 

    Try 
     wRequest = WebRequest.Create(Address) 
     wRequest.Timeout = 10000 
     wResponse = wRequest.GetResponse 
     SR = New StreamReader(wResponse.GetResponseStream) 
     rt = SR.ReadToEnd 
     SR.Close() 
    Catch wex As WebException 

     Dim status As WebExceptionStatus = wex.Status 

     If status = WebExceptionStatus.Timeout Then 
      MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Timed Out", MessageBoxButtons.OK, MessageBoxIcon.Warning) 
     ElseIf status = WebExceptionStatus.ConnectFailure Then 
      MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning) 
     ElseIf status = WebExceptionStatus.ProtocolError Then 
      MessageBox.Show("Could not establish a connection to the selected exchange server.", "Connection Protocol Error", MessageBoxButtons.OK, MessageBoxIcon.Warning) 

     End If 

    End Try 
+0

你能發佈異常的完整堆棧跟蹤嗎? – antiduh

+0

@antiduh我對VB.net有點新,我怎麼能在VS 2012中做到這一點?在某處設置一箇中斷點? –

回答

0

你的錯誤的來源爲Y我們的Address變量。 請在前面嘗試前綴http://

例子:

Address = "http://www.google.com" 

更多詳細信息,請參閱MSDN WebRequest.Create Method (String)

+0

這隻有在網站使用HTTP時纔是正確的。 – DeanOC

0

我檢查你的代碼,它工作正常。

這裏有一個demo雖然我做了time變量的聲明一點點變化,並把一個字符串在WebRequest.Create()像:

Dim time As Date = Now 

WebRequest.Create("https://www.google.fm") 

而且按我自己的搜索有沒有什麼需要關注的這種錯誤,請參閱下面的鏈接。

A first chance exception

0

的問題是最有可能的wResponse.GetResponseStream失敗,因爲wResponse爲空。 (這可能是因爲你的地址變量無效)。

嘗試增加

Catch ex As Exception 

    MessageBox.Show("Some other error occurred: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Warning) 

End Try 

您引發WebException Catch塊後,看是什麼問題。

或者只是在SR = New StreamReader(wResponse.GetResponseStream)上放一個斷點,然後看看wResponse(您的選擇)。

+0

我設置函數的方式,我用這樣的按鈕傳遞地址變量到函數'textbox1.text = getData(「http://somesite.com」)' –

+0

我不知道這是如何涉及到你的'null ref'異常。如果網站可以由用戶輸入,則應始終針對輸入無效地址並處理該地址的情況進行編碼。 – DeanOC

相關問題