Skip to content

Instantly share code, notes, and snippets.

Created December 3, 2014 11:57
Show Gist options
  • Save lesagesander/13911880aaf2adb5fc78 to your computer and use it in GitHub Desktop.
Save lesagesander/13911880aaf2adb5fc78 to your computer and use it in GitHub Desktop.
Reading and uploading a file with REST (c#)
//read file
Console.Write("Enter file path: ");
var filePath = Console.ReadLine();
filePath = String.IsNullOrEmpty(filePath) ? "C:\\Users\\Sander\\Desktop\\test.docx" : filePath;
var byteArray = File.ReadAllBytes(filePath);
//prep REST endpoint
var addFileInFolder =
String.Format("_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/folders(@TargetFolderName)/files/add(url=@TargetFileName,overwrite='{3}')?" +
"@TargetLibrary='{0}'&@TargetFolderName='{1}'&@TargetFileName='{2}'",docLibName, folderName, fileName, true);
//prepare webrequest.
//SharePoint site collection url
var spSite = new Uri(siteUrl);
//authenticate with SPO user.
var success = SpoAuthUtility.Create(spSite, userName, WebUtility.HtmlEncode(password), false);
Console.WriteLine("---Authentication passed: {0} ---", success);
if (success)
//get X-RequestDigest, required for POST.
var formDigest = SpoAuthUtility.GetRequestDigest();
//1. Upload file.
//prep rest call
var url = new Uri(String.Format("{0}/{1}", SpoAuthUtility.Current.SiteUrl, addFileInFolder));
Console.WriteLine("REST Call addFile: {0}\n\n", url);
//prep headers for addFile POST request
var headers = new Dictionary<String, String> { { "binaryStringRequestBody", "true" }, { "X-RequestDigest", formDigest } };
// Send a json odata request to SPO rest services to upload a file to a document library.
// pass in the helper object that allows us to make authenticated calls to SPO rest services
var result = HttpHelper.SendODataJsonRequest(
"POST", //writing data to SharePoint.
(HttpWebRequest) WebRequest.Create(url),
var response = Encoding.UTF8.GetString(result, 0, result.Length);
Console.WriteLine("\n---File added---");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment