mardi 24 mars 2015

GetFileByServerRelativeUrl returns corrupt document

I'm trying to read a SharePoint document using GetFileByServerRelativeUrl. The code seems to work (it throws no exceptions). It's returning a byte array that should represent a Word document. (It's eventually going to be used from a CRM plugin assuming I get this working and barring plugin sandbox restrictions.) The code is below.

public byte[] GetFileContent(string site, string libraryName, string folderName, string fileName)
_spo = SpoAuthUtility.Create(new Uri(site), _username, WebUtility.HtmlEncode(_password), false);

var digest = _spo.GetRequestDigest();

var getFileUrl =
string.Format("_api/web/GetFileByServerRelativeUrl('/sites/dev/library/folder/" + fileName + "')/$value");

var url = new Uri(String.Format("{0}/{1}", _spo.SiteUrl, getFileUrl));

var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Accept = "application/octet-stream";
webRequest.Headers.Add("X-RequestDigest", digest);
webRequest.Headers.Add("binaryStringResponseBody", "true");

var result = HttpHelper.SendODataJsonRequest(url, "GET", null, webRequest, _spo);
return result;


If I take the result of the function GetFileContent above when reading a Word document and do a File.WriteAllBytes with the result and try to open the file, Word says the file is corrupt. If I take the result of a text file (.txt) and do a File.WriteAllBytes, it works just fine and opens in notepad. I have set "binaryStringResponseBody" in the request header. If I read the word doc file from my hard drive using File.WriteAllBytes and write it back out, it opens fine. The word doc in SP is good - clicking on it's link opens it just fine in Word online, so that's not the issue. If I open the value of url.AbsoluteUri in my browser, it downloads a file. I rename it to have a .docx extension and it opens. It only fails when I read it from SharePoint. Any ideas?

0 commentaires:

Enregistrer un commentaire