Below are 2 code snippets used to check if a folder exists in a SharePoint document library. The PROPFIND method seems to work, while the other method, using HEAD results in a 401.
Can someone please tell me why? Don't get distracted by the credentials, I've set it to the same in both examples, and it works fine....
Here is the code that works:
// Create the web request object
var oReq = (HttpWebRequest)WebRequest.Create(url);
// Set the needed properties
oReq.Method = "PROPFIND";
oReq.Credentials = this.wsLists.Credentials; // Use same credentials as wsLists.
oReq.AllowAutoRedirect = true;
oReq.UserAgent = "Microsoft-WebDAV-MiniRedir/6.1.7600";
// Enumerate through top level only, increasing the depth will find children.
oReq.Headers["Depth"] = "0";
oReq.Headers["translate"] = "f";
var oRequest = new StreamWriter(oReq.GetRequestStream());
oRequest.WriteLine();
oRequest.Close();
var oResponse = new StreamReader(oReq.GetResponse().GetResponseStream());
string sResponse = oResponse.ReadToEnd();
oResponse.Close();
and here is the offending code:
private bool MossResourceExists(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(this.Domain ))
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password , this.Domain )
);
}
else
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password )
);
}
request.Credentials = myCredentialCache;
try
{
request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
return false;
else
throw new Exception("Error checking if URL exists:" + url + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message ) ;
}
return true;
}