Specified argument is out of the range of valid values. Parameter name: Server Relative URL

Josh Price picture Josh Price · Jan 4, 2013 · Viewed 11k times · Source

I am trying to download a document from a SharePoint document library using MVC however whenever I try to run my code I get the error mentioned above. I am new to SharePoint so please be nice. here is my code:

Web helper:

public Stream DownloadDocument(string SiteURL, string documentName)
{
  ListItem item = GetDocumentFromSP(documentName);

  if (item != null) {
    using (ClientContext clientContext = new ClientContext(SiteUrl)) {
      FileInformation fileInformation = 
        Microsoft.SharePoint.Client.File.OpenBinaryDirect(
          clientContext, 
          item["My Document.docx"].ToString()
        );

      return fileInformation.Stream;
    }
  }

  return null;
}

Controller:

public ActionResult Index() 
{
  Stream documentDownload = 
    WebHelper.DownloadDocument(
      "http://MySharePointServer/Docs/Forms/AllItems.aspx", 
      "My Document"
  );

  model.downloadedDoc = documentDownload;

  return view(model)
}

Answer

David Sterling picture David Sterling · Jan 5, 2013

This line:

Microsoft.SharePoint.Client.File.OpenBinaryDirect(
          clientContext, 
          item["My Document.docx"].ToString()

Is wrong, the proper syntax is to specify the Server Relative URL to the file:

public static FileInformation OpenBinaryDirect(
    ClientContext context,
    string serverRelativeUrl
)

Your line should look something like this:

Microsoft.SharePoint.Client.File.OpenBinaryDirect(
      clientContext, 
      "/My Document.docx"

David Sterling - http://davidmsterling.blogspot.com - http://www.sterling-consulting.com - http://www.sharepoint-blog.com