Upload a file in SharePoint using REST and c# console application

Hi,

In my last post, I have explained how to create a sub site using REST from and Console application. In this blog  will explain how we can upload a file, which is located in file system, will be uploaded to sharepoint Document library. So if I brief about requirement here:

  • Need to upload a file to already created SharePoint site.

  • Use REST(not even CSOM) will be used in order to create.

  • API call will be send from some other machine(not SharePoint machine) which is in same domain and can access the SharePoint site.


Follow the given steps to achieve the same:

1) Create a simple console application with c# selected language.

1

2) Next is to install the Newtonsoft.Json. Navigate to Visual studio menu: "View" > "Other Windows" > "Package Manager Console" and Then type the following: "Install-Package Newtonsoft.Json"

2

3) Now install RestSharp using the package manager. Type the following: "Install-Package RestSharp"

3

4) Now open the Program.cs file of console application and paste the code below:

string siteurl = "http://sharepoitsite/sites/subsite"; //site on which file needs to be uploaded (don't put / at end)
string documentlibrary = "Documents"; //Document library where file needs to be uploaded

string filePath = @"C:\Users\mohit.vashishtha\Desktop\test.html";

byte[] binary = System.IO.File.ReadAllBytes(filePath);
string fname = System.IO.Path.GetFileName(filePath);
string result = string.Empty;
//Url to upload file
string resourceUrl = string.Format("{0}/_api",siteurl);

RestClient RC = new RestClient(resourceUrl);
NetworkCredential NCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
RC.Authenticator = new NtlmAuthenticator(NCredential);

Console.WriteLine("Creating Rest Request");
RestRequest Request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
Request.AddHeader("Accept", "application/json;odata=verbose");
Request.AddHeader("Body", "");

string ReturnedStr = RC.Execute(Request).Content;
int StartPos = ReturnedStr.IndexOf("FormDigestValue") + 18;
int length = ReturnedStr.IndexOf(@""",", StartPos) - StartPos;
string FormDigestValue = ReturnedStr.Substring(StartPos, length);

Console.WriteLine("Uploading file Site......");

resourceUrl = string.Format("/web/GetFolderByServerRelativeUrl('{0}')/Files/add(url='{1}',overwrite=true)", documentlibrary ,fname);
Request = new RestRequest(resourceUrl, Method.POST);
Request.RequestFormat = DataFormat.Json;
Request.AddHeader("Accept", "application/json;odata=verbose");
Request.AddHeader("X-RequestDigest", FormDigestValue);
Console.WriteLine("File is successfully uploaded to sharepoint site.");
Console.ReadLine();

5) Now application is ready to run. Make sure that all the namespace issues are resolved.

6) It will take some time to create site but output window will display the details it got from the Request.

In case of already existing site:

54

Hope this information is helpful to you. Thanks for time.

Happy SharePointing :-)

 

Comments

  1. Hi could you please explain what this peice of code does ? i get an error here " Index was out of range. Must be non-negative and less than the size of the collection."

    string ReturnedStr = RC.Execute(Request).Content;
    int StartPos = ReturnedStr.IndexOf("FormDigestValue") + 18;
    int length = ReturnedStr.IndexOf(@""",", StartPos) - StartPos;
    string FormDigestValue = ReturnedStr.Substring(StartPos, length);

    ReplyDelete
  2. Creating Rest Request
    Uploading file Site..
    File is successfully uploaded to sharepoint site.

    All sucess messages but file not uploaded to sponline site!!! no error is displayed..

    ReplyDelete
  3. The same. First, I got error: 'Index was out of range.", but after - succesful, but file didnt upload :(

    ReplyDelete
  4. Yes, because the code is obviously incomplete. There is no actual second request to commit file upload. The binary file is never used..

    ReplyDelete

Post a Comment

Popular posts from this blog

Hide Ribbon on SharePoint 2013 using CSS

Get Comment Count in SharePoint

Configure external site as content sources in sharepoint search