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?


So using code that I found elsewhere bit me (not the code's fault, but my own.) The function HttpHelper.SendODataJsonRequest returns an array of bytes encoded in UTF-8.

Since my ultimate goal was to be able to create a zip file (in memory), I created a version of that function that returns the web response and used that to get a stream which I could use with the System.IO.Compression ZipArchive classes to create my zip file (or for testing purposes write to a file stream.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.