Reading and uploading a file with REST (c#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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