Sharepoint - SaveBinaryDirect Throws Unauthorized When the Client Object Model Works fine

If you are using SharePoint 2013 you cannot use SaveBinaryDirect, it does not work with claims authentication. The call made by SaveBinaryDirect does not include the required authorization cookies. Details are discussed in the comments to this blog post: How to do active authentication to Office 365 and SharePoint Online

Update (July 2, 2016):

I took another look at this after seeing the comment by James Love. I'm not sure what changed but my test indicates that SaveBinaryDirect is now working with SharePoint 2013 and SharePoint Online.

Here's the code I used:

// var context = new ClientContext("http://intranet.wingtip.com/sites/demo/");
// context.Credentials = System.Net.CredentialCache.DefaultCredentials;

var context = new ClientContext("https://robwindsor2.sharepoint.com/sites/demo/");
context.Credentials = new SharePointOnlineCredentials(loginName, securePassword);

var web = context.Web;
var lib = web.Lists.GetByTitle("Documents");

context.Load(lib);
context.Load(lib.RootFolder);
context.ExecuteQuery();

var fileName = "Test.docx";
var filePath = @"C:\Users\robwindsor\Desktop\" + fileName;
using (var fs = new FileStream(filePath, FileMode.Open))
{
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, lib.RootFolder.ServerRelativeUrl + "/" + fileName, fs, true);
}

var query = new CamlQuery();
query.ViewXml = "<View></View>";
var files = lib.GetItems(query);

context.Load(files, c => c.Include(f => f.File));
context.ExecuteQuery();

foreach(ListItem item in files)
{
    Console.WriteLine(item.File.Name);
}

Console.WriteLine("Done");        

Try this:

FileCreationInformation fci = new FileCreationInformation();

fci.Content = newFile.Bytes;

fci.Url = sourceFile.Url;

fci.Overwrite = true;

Microsoft.SharePoint.Client.File replacedFile = list.RootFolder.Files.Add(fci);

context.Load(replacedFile);

context.ExecuteQuery();

Tags:

File Upload