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?
NetworkCredentialsorHeader?
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>