Click here to Skip to main content
Licence CPOL
First Posted 7 May 2009
Views 29,784
Downloads 639
Bookmarked 26 times

How to Download a File from a WebDAV Server in VB.NET

By | 7 May 2009 | Article
This article demonstrates how to download a file from a (HTTPS) WebDAV server in VB.NET

Introduction

My company recently moved our FTP site to a secure WebDAV server (Web-based Distributed Authoring and Versioning). I was tasked with developing some automated download software. I thought there would be plenty of examples on the internet of how to do this, but was surprised to realize the difficulty I was having finding enough information. Because it took me a while to piece it together, I thought I would share my solution with others who may have similar needs.

Although there may be different ways for accessing and downloading information from a WebDAV server, I chose to use HTTPS, and have built this demo around that.

Background

If you are familiar with HttpWebRequest and HttpWebResponse, then you should feel right at home. The only difference between a regular server request and a WebDAV server request is that "Translate: f" header must be added, along with setting SendChunks = True.

If you're new to downloading files from a WebDAV server, then just follow along. I've included a demo that you can download and walk through to see how it works. The demo was created with VS 2008, Visual Basic, .NET Framework 2.0.

Using the Code

This first thing we can do is combine our URL and port, if a port was provided:

'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

Next, we can request the file from the WebDAV server.

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)

After the server has given us a response, we can begin to download the file.

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

Finally, after we have the file downloaded, perform a little validation just to make sure everything worked as expected.

'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

Conclusion

I hope this demo helps you out in your endeavors. If this works for you and you would like to know how to upload a file to a WebDAV server, then please see my article on that.

VBRocks
2008, 2009 Microsoft Visual Basic MVP

History

  • 7th May, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

VB Rocks

Software Developer
DataPrint, LLC
United States United States

Member

My blog: http://www.garylima.blogspot.com/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralList Files/Directories Pinmemberkuser21:46 15 Oct '09  
GeneralRe: List Files/Directories PinmemberVB Rocks3:45 29 Oct '09  
GeneralRe: List Files/Directories Pinmemberkuser4:04 29 Oct '09  
GeneralRe: List Files/Directories PinmemberVB Rocks4:07 29 Oct '09  
GeneralRe: List Files/Directories Pinmemberkuser4:20 29 Oct '09  
GeneralRe: List Files/Directories PinmemberSgtKashim9:03 28 Oct '11  
GeneralWebDAV client in C# Pinmemberkeesvdb22:30 10 Aug '09  
GeneralRe: WebDAV client in C# PinmemberVB Rocks3:43 11 Aug '09  
GeneralProtocol error PinmemberMichael Thomsen4:27 10 Jun '09  
GeneralRe: Protocol error PinmemberMichael Thomsen4:32 10 Jun '09  
GeneralRe: Protocol error PinmemberVB Rocks4:09 11 Jun '09  
GeneralRe: Protocol error PinmemberMichael Thomsen3:59 12 Jun '09  
GeneralRe: Protocol error PinmemberVB Rocks10:29 12 Jun '09  
GeneralRe: Protocol error Pinmemberhpatel399:24 29 Oct '09  
GeneralRe: Protocol error PinmemberVB Rocks7:14 30 Oct '09  
GeneralTwo questions PinmemberMichael Thomsen8:31 8 Jun '09  
GeneralRe: Two questions PinmemberVB Rocks5:58 9 Jun '09  
GeneralRe: Two questions PinmemberMichael Thomsen6:30 10 Jun '09  
GeneralRe: Two questions PinmemberVB Rocks3:48 11 Jun '09  
GeneralRe: Two questions Pinmemberkuser4:35 28 Oct '09  
GeneralRe: Two questions PinmemberVB Rocks3:45 29 Oct '09  
GeneralPerfect PinmemberMichael Thomsen8:30 8 Jun '09  
GeneralThanks :-) Pinmemberdr_oli3:44 15 May '09  
GeneralRe: Thanks :-) PinmemberVB Rocks6:00 9 Jun '09  
GeneralAdditional Resource PinmemberS1mm0t2:01 13 May '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120528.1 | Last Updated 7 May 2009
Article Copyright 2009 by VB Rocks
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid