File Upload to SharePoint Document Library (O365 Site) using C# Console - Rest API

Create a Console Application In Visual Studio and follow the below codes.

You will not find the "Newtonsoft.Json" references in the default reference files. You need to follow the below instruction to include Newstonsoft.json in the Console Application

Instructions for Adding Newstonsoft.Json

Via the "Solution Explorer"
  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type "json.net"
  4. Click "Install" and you're done.
Via the "Package Manager Console"
  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
  3. Install-Package Newtonsoft.Json
  4. For more info on how to use the "Package Manager Console" check out the nuget docs.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

static void Main(string[] args)
{
            
            string siteURL = "https://SomeSite.sharepoint.com/sites/internaldevelopersite/";
            string documentlibrary = "Shared Documents";
            string filePath = @"C:\Folder\Demo_File.txt";

            bool filestatus = UploadUsingRest(siteURL, documentlibrary, filePath);
            if (filestatus)
            {
                Console.WriteLine("File uploaded successfully");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Error uploading file");
                Console.ReadLine();
            }
}

public static bool UploadUsingRest(string siteurl, string libraryName, string filePath)
{
            bool status = false;
            byte[] binary = System.IO.File.ReadAllBytes(filePath);
            string fname = System.IO.Path.GetFileName(filePath);
            string result = string.Empty;
            string o365UserName = "YourEmailID";
            string o365Password = "YourPassword";
            var secureStr = new SecureString();

            foreach (char c in o365Password)
            {
                secureStr.AppendChar(c);
            }

            //Url to upload file
            string resourceUrl = siteurl + "/_api/web/GetFolderByServerRelativeUrl('"+ libraryName + "')/files/add(url='" + fname + "',overwrite=true)";
            HttpWebRequest HttpRequest = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
            HttpRequest.UseDefaultCredentials = false;

            SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(o365UserName, secureStr);
            HttpRequest.Credentials = credentials;

            string formDigest = GetFormDigestValue(siteurl, credentials);   //Get formdigest value from site
            HttpRequest.Headers.Add("X-RequestDigest", formDigest);
            HttpRequest.Method = "POST";
            HttpRequest.Timeout = 1000000; //timeout should be large in order to upload file which are of large size
            HttpRequest.Accept = "application/json; odata=verbose";
            HttpRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            HttpRequest.ContentLength = binary.Length;
            try
            {
                using (System.IO.Stream requestStream = HttpRequest.GetRequestStream())
                {
                    requestStream.Write(binary, 0, binary.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                WebResponse wresp = HttpRequest.GetResponse();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                    status = true;
                    return status;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return status;
                throw;
            }
}

private static string GetFormDigestValue(string siteurl, SharePointOnlineCredentials credentials)
{
            string newFormDigest = "";
            var GetFormDigestUrl = siteurl + "_api/contextinfo";
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(GetFormDigestUrl);
            endpointRequest.Method = "POST";
            endpointRequest.Headers.Add("Authorization", "BEARER" + newFormDigest);
            endpointRequest.ContentLength = 0;
            endpointRequest.Credentials = credentials;
            endpointRequest.ContentType = "application/json";
            endpointRequest.Accept = "application/json;odata=verbose";

            try
            {
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {

                WebResponse webResp = endpointRequest.GetResponse();
                Stream webStream = webResp.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                var j = JObject.Parse(response);
                var jObj = (JObject)JsonConvert.DeserializeObject(response);
                foreach (var item in jObj["d"].Children())
                {
                    newFormDigest = item.First()["FormDigestValue"].ToString();
                }
                responseReader.Close();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }

            return newFormDigest;
}

Notes:

When you use POST method, you will required accessToken, which is otherwise called as formDigest. The formDigest value prefix will start with "0x...".


Use the same code If you want to upload files to O365.  Incase if you work in On-Permise kindly use NetworkCredentials instead of SharePointOnlineCredentials.


Good Luck !

Comments

Popular Posts