Click here to Skip to main content
11,584,040 members (39,119 online)
Click here to Skip to main content

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

, 14 May 2009 CPOL 118.1K 3.5K 28
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

You may also be interested in...

Comments and Discussions

 
SuggestionLarger Files Pin
Member 1029413831-Jul-14 7:25
memberMember 1029413831-Jul-14 7:25 
GeneralWorks like a charm Pin
D. de Kerf2-Apr-13 21:31
memberD. de Kerf2-Apr-13 21:31 
QuestionWebDAV Pin
KevinBrady5711-Oct-12 6:15
memberKevinBrady5711-Oct-12 6:15 
AnswerRe: WebDAV Pin
VB Rocks11-Oct-12 6:48
memberVB Rocks11-Oct-12 6:48 
GeneralMy vote of 5 Pin
Omar Khaled28-Sep-12 0:53
memberOmar Khaled28-Sep-12 0:53 
GeneralMy vote of 5 Pin
Daniel Leykauf28-Jul-12 3:40
memberDaniel Leykauf28-Jul-12 3:40 
QuestionOverwrite option Pin
Gian Andrea21-Feb-12 23:00
memberGian Andrea21-Feb-12 23:00 
GeneralOutOfMemory exception Pin
vit vit22-Feb-11 3:31
membervit vit22-Feb-11 3:31 
GeneralGreat article VBRocks, but one question... Pin
jportelas23-Dec-10 1:26
memberjportelas23-Dec-10 1:26 
GeneralError 501 Not Implenented Errors Pin
Pokey8417-Oct-10 9:01
memberPokey8417-Oct-10 9:01 
QuestionHow can I use a progressbar with it? Pin
rezanew26-Jun-10 8:13
memberrezanew26-Jun-10 8:13 
GeneralExcellent example Pin
maxxnostra19-Feb-10 8:28
membermaxxnostra19-Feb-10 8:28 
GeneralI get response 200 OK. Pin
mrdance18-Jan-10 11:12
membermrdance18-Jan-10 11:12 
GeneralRe: I get response 200 OK. Pin
maxxnostra19-Feb-10 8:22
membermaxxnostra19-Feb-10 8:22 
GeneralC# Pin
hpatel3929-Oct-09 5:24
memberhpatel3929-Oct-09 5:24 
GeneralUpload File to a WebServer via https Pin
noobdev14-Jul-09 23:45
membernoobdev14-Jul-09 23:45 
AnswerRe: Upload File to a WebServer via https Pin
mmjd2-Aug-09 21:03
membermmjd2-Aug-09 21:03 
GeneralRe: Upload File to a WebServer via https Pin
maxxnostra19-Feb-10 8:13
membermaxxnostra19-Feb-10 8:13 
QuestionError 409 Pin
Ase229-May-09 0:10
memberAse229-May-09 0:10 
AnswerRe: Error 409 Pin
maxxnostra19-Feb-10 8:27
membermaxxnostra19-Feb-10 8:27 
Generalthanks Pin
JeffCirceo16-May-09 3:23
memberJeffCirceo16-May-09 3: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
Web03 | 2.8.150603.1 | Last Updated 14 May 2009
Article Copyright 2009 by CS Rocks
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid