Sunday, March 13, 2011

"The remote server returned an error: (401) Unauthorized." exception when you try to access a file in SharePoint Document Library

Scenario:
You receive an exception "The remote server returned an error: (401) Unauthorized." when you try to access a file in SharePoint Document Library.

Explanation:

When you try to access a document in a SharePoint site without anonymous access turned on in the below manner, you would receive a 401 unauthorized error.

XmlDocument xDocument = new XmlDocument();
xDocument.Load(String.Format("{0}{1}", SPContext.Current.Web.Url, XmlFileLocation));

Resolution:

Try to access the file as below:

SPFile configFile = SPContext.Current.Web.GetFile(String.Format("{0}{1}", SPContext.Current.Web.Url, XmlFileLocation));
XmlDocument xdoc = new XmlDocument();
byte[] fileBytes = configFile.OpenBinary();
Stream streamFile = new MemoryStream(fileBytes);
xdoc.Load(streamFile);






No comments:

Post a Comment