FTP上传完成后VB.NET显示消息

时间:2014-04-12 03:33:40

标签: vb.net ftp

我正在尝试为FTP创建一个上传器,虽然文件上传完美,我只是想知道在ftp进程完成后我将如何显示一条消息。

 Close()
        Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        Dim r As New Random
        Dim sb As New StringBuilder
        For i As Integer = 1 To 8
            Dim idx As Integer = r.Next(0, 35)
            sb.Append(s.Substring(idx, 1))
        Next


        Using ms As New System.IO.MemoryStream
            sc.CaptureDeskTopRectangle(Me.boundsRect).Save(ms, System.Drawing.Imaging.ImageFormat.Png)
            Using wc As New System.Net.WebClient
                wc.UploadData("ftp://MYUSERNAME:MYPASSWORD@MYSITE.COM/" + sb.ToString() + ".png", ms.ToArray())
            End Using
        End Using

我该如何处理?

编辑:另外你可以看到我使用随机字符串..虽然如果我使用sb.ToString()两次它会给我两个完全相同的结果?如果不是我怎么能管理这个??

1 个答案:

答案 0 :(得分:0)

您需要将Random声明为静态。 UploadData有一个UploadDataCompleted事件,你可以听。

    Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    Static r As New Random
    Dim sb As New StringBuilder
    For i As Integer = 1 To 8
        Dim idx As Integer = r.Next(0, 35)
        sb.Append(s.Substring(idx, 1))
    Next


    Using ms As New System.IO.MemoryStream
        sc.CaptureDeskTopRectangle(Me.boundsRect).Save(ms, System.Drawing.Imaging.ImageFormat.Png)
        Using wc As New System.Net.WebClient
            AddHandler wc.UploadDataCompleted, AddressOf UploadCompleted
            wc.UploadData("ftp://MYUSERNAME:MYPASSWORD@MYSITE.COM/" + sb.ToString() + ".png", ms.ToArray())
        End Using
    End Using

  Private Sub UploadCompleted(sender As Object, e As Net.UploadDataCompletedEventArgs)
    'do completed work here
  End Sub

我不认为你可以像这样使用UploadData。以下是ftp上传示例的Link

Public Shared Sub Main()
' Get the object used to communicate with the server.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://www.contoso.com/test.htm"), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile

' This example assumes the FTP site uses anonymous logon.
request.Credentials = New NetworkCredential("anonymous", "janeDoe@contoso.com")

' Copy the contents of the file to the request stream.
Dim sourceStream As New StreamReader("testfile.txt")
Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
sourceStream.Close()
request.ContentLength = fileContents.Length

Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(fileContents, 0, fileContents.Length)
requestStream.Close()

Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)

Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription)

response.Close()
End Sub