VB.net UploadFile

时间:2013-11-15 16:54:26

标签: vb.net upload

我正在尝试使用VB.net将文件发送到服务器。我发现很多例子说它很简单,但我发现的例子都没有。

我正在尝试的当前代码如下:

Dim WithEvents wc As New System.Net.WebClient()
Private Sub oWord_DocumentBeforeClose(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean) Handles oWord.DocumentBeforeClose
    Try

        Using wc As New System.Net.WebClient()
            wc.Credentials = New NetworkCredential("ehavermale", "ernie1")
            wc.UploadFile("http://192.168.95.1:83/GraphTest.txt", "C:\Users\EHovermale\Desktop\GraphTest.txt")
        End Using
    Catch ex As Exception
        MsgBox("Error:" + ex.Message)
    End Try

    'System.IO.File.Delete("C:\Users\EHovermale\Desktop\GraphTest.txt")

    MsgBox("See Ya")
End Sub

当我运行此程序时,我得到错误:WebClient请求期间发生了异常。

我可以访问我想要访问的服务器的读/写文件。

是否有其他方式上传文件或我的代码出错了?

谢谢!

1 个答案:

答案 0 :(得分:-1)

由于没有HTTP服务来处理文件上载,您可以使用VBA的Scripting.FileSystemObject直接保存文件。如果您可以从文档所在的任何位置访问网络共享,这将起作用。请记住,如果将文档移动到另一台计算机,则可能无法正常工作。

Public Sub MoveFile()

    Dim fso As Object
    Dim sourceFile As String
    Dim targetFile As String

    ' You must add reference to "Microsoft Scripting Runtime" to your document
    ' Tools > References... > scroll down the item.
    Set fso = CreateObject("Scripting.FileSystemObject")
    sourceFile = "C:\Users\davidr\Desktop\foo.txt"
    targetFile = "\\192.168.95.1:83\foo.txt"

    ' Test if destination file already exists
    If fso.FileExists(targetFile) Then
        MsgBox ("This file exists!")
        Exit Sub
    End If

    ' Move the file
    fso.CopyFile sourceFile, targetFile
    Set fso = Nothing

End Sub