Uploading file into SharePoint 2013 online, using an access token

There are two things I dislike about Microsoft.SharePoint.Client.File.SaveBinaryDirect()

WHY U HAVE NO ASYNC?

This blocks for network IO, and we should be able to use Async Await syntax to deal with this. Remember when we were told we had to stop using ServerOM, and then Sandbox? Biggest argument was that we would be able to use all the cool new stuff from the latest version of .NET, as we wouldn’t be constrained by the .NET 3.5 and old school SharePoint internals … YEAH – So why am I still waiting for ASYNC methods on the C# client sdk? </rant>

It doesn’t seem to work nicely with ClientContext’s loaded using an access token.

If you are using the Magical TokenHelper.cs, and grab a ClientContext using an accesstoken, most of the stuff just works great. Apart from SaveBinaryDirect; here, we just get a bunch of errors.

Anyway.

Solution:

Something like this:


public async static Task UploadUsingAccessTokenAsync(string siteCollectionUrl, string serverRelativeFolder, string filename, string accessToken, byte[] data)
{
System.Net.ServicePointManager.Expect100Continue = false;
var requestUrl = string.Format("{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/Add(url='{2}', overwrite=true)", siteCollectionUrl, serverRelativeFolder, filename);
HttpWebRequest request = HttpWebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = "application/json;odata=verbose";
request.ContentLength = data.Length;
request.Headers.Add("Authorization", "Bearer " + accessToken);
using (Stream req = await request.GetRequestStreamAsync().ConfigureAwait(false))
{
await req.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
}
using (HttpWebResponse response = (await request.GetResponseAsync().ConfigureAwait(false)) as HttpWebResponse)
{
using (Stream res = response.GetResponseStream())
{
using (StreamReader rdr = new StreamReader(res))
{
return await rdr.ReadToEndAsync().ConfigureAwait(false);
}
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s