WebDAV服务器文件下载示例

在开发自动化下载软件的过程中,发现网络上关于如何从WebDAV服务器下载文件的示例并不多。因此,决定分享解决方案,以帮助那些可能有类似需求的人。

虽然访问和下载WebDAV服务器上的信息可能有多种方式,但选择了使用HTTPS,并围绕此构建了这个示例。

如果熟悉HttpWebRequestHttpWebResponse,那么应该会对这个过程感到熟悉。普通服务器请求与WebDAV服务器请求的唯一区别在于必须添加"Translate: f"头部,并且设置SendChunks = True

如果是第一次从WebDAV服务器下载文件,那么请跟随本文的步骤。包含了一个可以下载并逐步查看其工作原理的示例。该示例是用VS 2008、Visual Basic和.NET Framework 2.0创建的。

使用代码

首先,可以组合URL和端口(如果提供了端口):

Dim url As String = "https://someSecureTransferSite.com/fileToDownload.dat" Dim port As String = "443" If port <> "" Then Dim u As New Uri(url) Dim host As String = u.Host url = url.Replace(host, host & ":" & port) End If

接下来,可以从WebDAV服务器请求文件:

Dim userName As String = "UserName" Dim password As String = "Password" Dim request As HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(url), HttpWebRequest) request.Credentials = New NetworkCredential(userName, password) request.Method = WebRequestMethods.Http.Get request.SendChunked = True request.Headers.Add("Translate: f") Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

服务器响应后,可以开始下载文件:

Dim destination As String = "c:\temp\downloadedFile.dat" Dim byteTransferRate As Integer = 4096 Dim bytes(byteTransferRate - 1) As Byte Dim bytesRead As Integer = 0 Dim totalBytesRead As Long = 0 Dim contentLength As Long = 0 contentLength = CLng(response.GetResponseHeader("Content-Length")) Dim fs As New IO.FileStream(destination, IO.FileMode.Create, IO.FileAccess.Write) Dim s As IO.Stream = response.GetResponseStream() Do bytesRead = s.Read(bytes, 0, bytes.Length) If bytesRead > 0 Then totalBytesRead += bytesRead fs.Write(bytes, 0, bytesRead) End If Loop While bytesRead > 0 s.Close() s.Dispose() s = Nothing fs.Close() fs.Dispose() fs = Nothing response.Close() response = Nothing

进行一些验证,以确保一切按预期工作:

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 MessageBox.Show("The file has downloaded successfully!", "Download Complete", MessageBoxButtons.OK, MessageBoxIcon.Information) End If

希望这个示例能帮助。如果这对有作用,并且想知道如何上传文件到WebDAV服务器,请参考关于该主题的文章。

沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485