Search code examples
c#.netwinformsapachewebdav

Uploading a file to WebDAV server using WebClient.UploadFile returns 401


I try to upload files from my C# application on a Windows client to a Linux webserver through WebDAV. To achieve this I am using WebClient.UploadFile(). The upload always throws an exception:

The remote server returned an error: (401) Unauthorized

I tried two different methods of authorization both with the same result.

Authorization:

// Method A
myWebClient.Credentials = new NetworkCredential("user123", "pass123");

// Method B
var bytes = Encoding.UTF8.GetBytes(String.Format("{0}:{1}", "user123", "pass123"));
string auth = Convert.ToBase64String(bytes);
// "Basic aW1hZ2VfdXBsb2FkOkozMkUzYnVGWlB1S0tkQ2tQRkpV"
string authString = String.Format("Basic {0}", auth); 
myWebClient.Headers.Add("Authorization", authString);

To ensure WebDAV is working as intended, I connected and uploaded files using WinSCP (Windows GUI) and cadaver (Linux terminal) both with success.


File upload code:

try
{
    string address = "http://123.124.125.126/webdav/1";
    string fileName = "F:\\articleimages\\isotope\\1\\1dmgo.jpg";
    byte[] response = myWebClient.UploadFile(address, fileName);
}
catch (WebException wexc)
{
    // wexc.Message == The remote server returned an error: (401) Unauthorized
}

Questions

  • Is my code correct so far?
  • Which authorization I am expected to use? NetworkCredentials or Header?

Since the concept is only failing in my C# application the problem must lie there.

  • How would I troubleshoot further more?

The actual response (Exception details)

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

Solution

  • WebClient is an HTTP Client, not a WebDAV client.

    If you do WebClient.UploadFile, it by default uses HTTP POST request, not WebDAV PUT request.

    The authentication failure can be just a side effect of that. And even if not, and you solve the authentication problem, it would probably not help you.

    I do not know if it can help, but try using an overload that takes method argument and use "PUT".


    Another option, as WinSCP works for you, is using WinSCP .NET assembly.