Skip to content

Instantly share code, notes, and snippets.

@lesagesander
Created December 3, 2014 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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.
try
{
//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(
url,
"POST", //writing data to SharePoint.
byteArray,
(HttpWebRequest) WebRequest.Create(url),
SpoAuthUtility.Current,
headers
);
var response = Encoding.UTF8.GetString(result, 0, result.Length);
Console.WriteLine(response);
Console.WriteLine("\n---File added---");
}
catch{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment