我的FTP客户端遇到了一个小问题 选择文件有效,用4个变量重命名该文件 这是导致我麻烦的上传内容。 每当文件上传到FTP服务器时,它都说是0KB。
我在考虑两个可能的问题:
Visual Studio告诉我变量file
在赋值之前使用,以确保它不是null我执行了以下操作。
Dim file As Byte()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
这可以解决任何可能的错误。
第二个是fName,与文件相同的警告,我以同样的方式处理它。
另一种可能性是我的代码只接受4个变量并将其转换为文件并上传它,因此大小为0KB ....
这是我的代码:
Dim Filename As String
Dim originalFile As String
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is ComboBox AndAlso DirectCast(Control, ComboBox).SelectedIndex > -1) Then
fName += CStr(Control.SelectedItem.Key) + "_"
End If
Next
Try
fName = path + fName.Substring(0, fName.Length - 1) + ".jpg"
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
MsgBox(enumerateCheckboxes(Filename))
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ip" & enumerateCheckboxes(Filename)), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
If (Not Filename Is Nothing) Then
System.IO.File.ReadAllBytes(Filename)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
If (Not Filename Is Nothing) Then
FileSystem.Rename(originalFile, Filename)
End If
Dim strz As System.IO.Stream = request.GetRequestStream()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
End Sub
End Class
我看过多个与我有同样问题的线程。
像this这样的主题
但我不相信这适用于我的问题。
如果你能如此善意地解释我做错了什么以及我将来如何解决和避免这种情况,我的调试仍然有点粗糙......
提前谢谢!
答案 0 :(得分:2)
Visual Studio正在向您发出警告,因为您从未向file
数组分配任何内容。我认为就在你所拥有的那条线上:
System.IO.File.ReadAllBytes(Filename)
你真的打算:
file = System.IO.File.ReadAllBytes(Filename)