Click here to Skip to main content
Click here to Skip to main content

How to Upload a File to a WebDAV Server in VB.NET

, 14 May 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This article demonstrates how to upload a file to 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, which lead to uploading as well. I thought there would be plenty of examples on the internet on 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.

To learn how to download a file from a WebDAV server, please see my article How to Download a File from a WebDAV server in VB.NET.

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 the "Translate: f" header must be added, along with setting SendChunks = True and AllowWriteStreamBuffering = True.

If you're new to uploading files to 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, and .NET Framework 2.0.

Using the code

The first thing we need to do is get the path of the file, and its length.

Dim fileToUpload As String = "c:\temp\transfer me.zip"
Dim fileLength As Long = My.Computer.FileSystem.GetFileInfo(fileToUpload).Length

Next, we need to get the URL and the port, and combine them if a port was provided.

Dim url As String = "https://someSecureTransferSite.com/directory"
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:80/directory
     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

Add the name of the file we are uploading to the end of the URL. This creates a "target" file name.

url = url.TrimEnd("/"c) & "/" & IO.Path.GetFileName(fileToUpload)

Create a request for the WebDAV server for the file we want to upload.

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 "put" a file on it
request.Method = WebRequestMethods.Http.Put

'Set the length of the content (file) we are sending
request.ContentLength = fileLength


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


'Send the request to the server, and get the 
' server's (file) Stream in return.
Dim s As IO.Stream = request.GetRequestStream()

After the server has given us a stream, we can begin to write to it.

Note: The data is not actually being sent to the server here, it is written to a stream in memory. The data is actually sent below when the response is requested from the server.

'Open the file so we can read the data from it
Dim fs As New IO.FileStream(fileToUpload, IO.FileMode.Open, _
                            IO.FileAccess.Read)

'Create the buffer for storing the bytes read from the file
Dim byteTransferRate As Integer = 1024
Dim bytes(byteTransferRate - 1) As Byte
Dim bytesRead As Integer = 0
Dim totalBytesRead As Long = 0

'Read from the file and write it to the server's stream.
Do
    'Read from the file
    bytesRead = fs.Read(bytes, 0, bytes.Length)

    If bytesRead > 0 Then

        totalBytesRead += bytesRead

        'Write to stream
        s.Write(bytes, 0, bytesRead)

    End If

Loop While bytesRead > 0

'Close the server stream
s.Close()
s.Dispose()
s = Nothing

'Close the file
fs.Close()
fs.Dispose()
fs = Nothing

Now, although we have finished writing the file to the stream, the file has not been uploaded yet. If we exit here without continuing, the file would not be uploaded.

The last step we have to perform is sending the data to the server.

  • When we request a response from the server, we are actually sending the data to the server, and receiving the server's response in return.
  • If we do not perform this step, the file would not be uploaded.
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

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

'Get the StatusCode from the server's Response
Dim code As HttpStatusCode = response.StatusCode

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

'Validate the uploaded file.
' Check the totalBytesRead and the fileLength: Both must be an exact match.
'
' Check the StatusCode from the server and make sure the file was "Created"
' Note: There are many different possible status codes. You can choose
' which ones you want to test for by looking at the "HttpStatusCode" enumerator.
If totalBytesRead = fileLength AndAlso _
    code = HttpStatusCode.Created Then

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

Else

    MessageBox.Show("The file did not upload successfully.", _
        "Upload Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning)

End If

Conclusion

I hope this demo helps you out in your endeavors!

Remember to see my other article: How to download a File from a WebDAV Server in VB.NET.

License

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

Share

About the Author

CS Rocks
Software Developer DataPrint, LLC
United States United States

Comments and Discussions

 
SuggestionLarger Files PinmemberMember 1029413831-Jul-14 8:25 
GeneralWorks like a charm PinmemberD. de Kerf2-Apr-13 22:31 
QuestionWebDAV PinmemberKevinBrady5711-Oct-12 7:15 
AnswerRe: WebDAV PinmemberVB Rocks11-Oct-12 7:48 
GeneralMy vote of 5 PinmemberOmar Khaled28-Sep-12 1:53 
GeneralMy vote of 5 PinmemberDaniel Leykauf28-Jul-12 4:40 
QuestionOverwrite option [modified] PinmemberGian Andrea22-Feb-12 0:00 
GeneralOutOfMemory exception Pinmembervit vit22-Feb-11 4:31 
GeneralGreat article VBRocks, but one question... Pinmemberjportelas23-Dec-10 2:26 
GeneralError 501 Not Implenented Errors PinmemberPokey8417-Oct-10 10:01 
QuestionHow can I use a progressbar with it? Pinmemberrezanew26-Jun-10 9:13 
GeneralExcellent example Pinmembermaxxnostra19-Feb-10 9:28 
GeneralI get response 200 OK. Pinmembermrdance18-Jan-10 12:12 
GeneralRe: I get response 200 OK. Pinmembermaxxnostra19-Feb-10 9:22 
GeneralC# Pinmemberhpatel3929-Oct-09 6:24 
GeneralUpload File to a WebServer via https Pinmembernoobdev15-Jul-09 0:45 
AnswerRe: Upload File to a WebServer via https Pinmembermmjd2-Aug-09 22:03 
GeneralRe: Upload File to a WebServer via https Pinmembermaxxnostra19-Feb-10 9:13 
QuestionError 409 PinmemberAse229-May-09 1:10 
AnswerRe: Error 409 Pinmembermaxxnostra19-Feb-10 9:27 
Generalthanks PinmemberJeffCirceo16-May-09 4:23 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 14 May 2009
Article Copyright 2009 by CS Rocks
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid