65.9K
CodeProject 正在变化。 阅读更多。
Home

如何在 VB.NET 中从 WebDAV 服务器下载文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (13投票s)

2009年5月7日

CPOL

2分钟阅读

viewsIcon

118177

downloadIcon

2685

本文演示了如何在 VB.NET 中从 (HTTPS) WebDAV 服务器下载文件。

引言

我们公司最近将我们的 FTP 站点迁移到安全的 WebDAV 服务器(基于 Web 的分布式创作和版本控制)。我被要求开发一些自动下载软件。我以为在互联网上会有很多关于如何操作的示例,但惊讶地发现很难找到足够的信息。由于我花了一段时间才将其拼凑起来,我想与可能有类似需求的人分享我的解决方案。

虽然可能有不同的方法来访问和下载 WebDAV 服务器上的信息,但我选择使用 HTTPS,并以此为基础构建了这个演示。

背景

如果您熟悉 HttpWebRequestHttpWebResponse,那么您会感到如鱼得水。常规服务器请求和 WebDAV 服务器请求之间的唯一区别是必须添加 "Translate: f" 标头,并设置 SendChunks = True

如果您不熟悉从 WebDAV 服务器下载文件,请按照操作步骤进行。我提供了一个演示,您可以下载并逐步了解其工作原理。该演示使用 VS 2008、Visual Basic 和 .NET Framework 2.0 创建。

Using the Code

首先,我们可以将我们的 URL 和端口组合起来,如果提供了端口的话。

'Get url and Port
Dim url As String = "https://someSecureTransferSite.com/fileToDownload.dat"
Dim port As String = "443"

'If the port was provided, then insert it into the url.
If port <> "" Then

    'Insert the port into the url
    'https://www.example.com:443/fileToDownload.dat
    Dim u As New Uri(url)

    'Get the host (example: www.example.com)
    Dim host As String = u.Host

    'Replace the host with the host:port
    url = url.Replace(host, host & ":" & port)

End If

接下来,我们可以从 WebDAV 服务器请求文件。

Dim userName As String = "UserName"
Dim password As String = "Password"

'Create the request
Dim request As HttpWebRequest = _
    DirectCast(System.Net.HttpWebRequest.Create(url), HttpWebRequest)

'Set the User Name and Password
request.Credentials = New NetworkCredential(userName, password)

'Let the server know we want to "get" a file
request.Method = WebRequestMethods.Http.Get

'*** This is required for our WebDAV server ***
request.SendChunked = True
request.Headers.Add("Translate: f")

'Get the response from the request
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

在服务器向我们提供响应后,我们可以开始下载文件。

Dim destination As String = "c:\temp\downloadedFile.dat"

'Create the buffer for storing the bytes read from the server
Dim byteTransferRate As Integer = 4096 '4096 bytes = 4 KB
Dim bytes(byteTransferRate - 1) As Byte
Dim bytesRead As Integer = 0 'Indicates how many bytes were read 
Dim totalBytesRead As Long = 0 'Indicates how many total bytes were read
Dim contentLength As Long = 0 'Indicates the length of the file being downloaded

'Read the content length
contentLength = CLng(response.GetResponseHeader("Content-Length"))

'Create a new file to write the downloaded data to
Dim fs As New IO.FileStream(destination, IO.FileMode.Create, _
       IO.FileAccess.Write)

'Get the stream from the server
Dim s As IO.Stream = response.GetResponseStream()

Do
    'Read from the stream
    bytesRead = s.Read(bytes, 0, bytes.Length)

    If bytesRead > 0 Then

        totalBytesRead += bytesRead

        'Write to file
        fs.Write(bytes, 0, bytesRead)

    End If

Loop While bytesRead > 0

'Close streams
s.Close()
s.Dispose()
s = Nothing

fs.Close()
fs.Dispose()
fs = Nothing

'Close the response
response.Close()
response = Nothing

最后,在下载完文件后,执行一些验证,以确保一切按预期工作。

'Validate the downloaded file. Both must be an exact match 
' for the file to be considered a valid download.
If totalBytesRead <> contentLength Then

     MessageBox.Show("The downloaded file did not download successfully, " & _
         "because the length of the downloaded file " & _
         "does not match the length of the file on the remote site.", _
         "Download File Validation Failed", _
         MessageBoxButtons.YesNo, MessageBoxIcon.Warning)

Else 'totalBytesRead = contentLength

     MessageBox.Show("The file has downloaded successfully!", "Download Complete", _
         MessageBoxButtons.OK, MessageBoxIcon.Information)

End If

结论

我希望这个演示对您有所帮助。如果此方法对您有效,并且想了解如何将文件上传到 WebDAV 服务器,请参阅我的相关文章。

VBRocks
2008 年、2009 年 Microsoft Visual Basic MVP

历史

  • 2009年5月7日:初始发布
© . All rights reserved.