Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
14 May 2009 4  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here