如何创建字符串VB.Net的实例

时间:2013-07-12 18:28:18

标签: vb.net string ftp instance

好的,我正在制作这个程序,自动从我的远程ftp服务器获取用户名和密码,并登录。但是它给了我一个错误,上面写着“对象引用没有设置为对象的实例”

以下是我的代码示例:

    Imports System.Net
    Imports System.Net.FtpClient
    Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Using ftp = New FtpClient()
        Dim credentials As New NetworkCredential
        ftp.Host = "my ftp server"
        credentials = ftp.Credentials
        Dim username As String
        username = credentials.UserName.ToString 'Object reference not set to an instance of an object
        Dim password As String
        password = credentials.Password.ToString
    End Using
End Sub    

2 个答案:

答案 0 :(得分:1)

我怀疑你的问题在这里:

' credentials = ftp.Credentials
' Should be:
ftp.Credentials = credentials

设置完成后,您需要输入凭据,而不是获取凭据:

Dim username As String = GetUserNameFromSomewhere()
credentials.UserName = username
' Same as password

现在,您正在创建NetworkCredential,然后“扔掉它”并将其替换为FtpClient凭据。由于您尚未对其进行设置,因此NothingUserName,当您尝试获取{{1}}时会导致异常。

答案 1 :(得分:0)

使用NetworkCredential设置它们不会从此对象中检索它们。这些凭据将传递给FtpClient。所以没有设置它们是Nothing因此错误。