C# REST Add File to SharePoint Library


If you can use C# and you are not developing for the mobile platform I would just use CSOM. it’s way easier to use than REST. It’s smart enough to know how to authenticate properly with or without ADFS.

I’m not 100% sure, but I think that in your case, you can probably download the file, but not upload it because you don’t add X-RequestDigest header to your request. Downloading the file does not require it, but any post does.

Here is an example that uses HttpClientHandler instead of the WebClient, but the idea is the same:

    public async Task<string> UploadFile(byte() image, string listTitle, string relativePath, string uploadFileName)
    {
        string endpointUrl = _siteUrl + String.Format(
           "/_api/web/GetFolderByServerRelativeUrl('{0}')/Files/Add(url='{1}', overwrite=true)",
           relativePath,
           uploadFileName);

        HttpClientHandler httpHandler = new HttpClientHandler();
        httpHandler.CookieContainer = cc;

        HttpClient client = new HttpClient(httpHandler);
        client.DefaultRequestHeaders.Add("X-RequestDigest", _DigestValue);

        try
        {
            ByteArrayContent imageBytes = new ByteArrayContent(image);
            var result = await client.PostAsync(endpointUrl, imageBytes);
            return result.Content.ToString();
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

Here is a basic example of playing with REST via C# that I’ve written a couple of years ago: