Reputation: 603
I have below code and i want to upload a file on sharepoint site in specific folder.
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.SharePoint.Client;
using MSharp.Framework.Services;
using RestSharp;
using RestSharp.Authenticators;
using System;
using System.IO;
using System.Net;
using System.Security;
namespace SharepointFileSend
{
class Program
{
private const string password = "XXX!";
private static string hostWeb = "XXX.sharepoint.com";
static void Main(string[] args)
{
string siteUrl = "http://XXX.sharepoint.com/sites"; //site on which file needs to be uploaded (don’t put / at end)
string documentlibrary = "Documents"; //Document library where file needs to be uploaded
var securePassword = new SecureString();
ClientContext context = new ClientContext(siteUrl);
foreach (var c in password.ToCharArray()) securePassword.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);
string sharePointDocPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "test.html");
byte[] binary = System.IO.File.ReadAllBytes(sharePointDocPath);
string fname = System.IO.Path.GetFileName(sharePointDocPath);
string result = string.Empty;
//Url to upload filef
string resourceUrl = string.Format("{0}/_api", siteUrl);
RestClient RC = new RestClient("http://XXXXX.sharepoint.com/_api");
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();
}
}
}
I am getting the output as : File is successfully uploaded to sharepoint site. But when i search the file in sharepoint ,file is not present. Please help improving this code.
Upvotes: 1
Views: 1294
Reputation: 101
I spent a lot of time trying to figure out how to upload a file to a subdirectory in a folder inside a document library. The code I posted uploads a binary stream to a file to a specific folder. Hope this helps.
public async Task UploadToSharePoint( Stream stream, SharePointOnlineCredentials creds, string url, string folder, string fileName )
{
try
{
var clientContext = new ClientContext( url)
{
Credentials = creds
};
var web = clientContext.Web;
// load the site lists
clientContext.Load(web, website => website.Lists, website => website.ServerRelativeUrl);
await clientContext.ExecuteQueryAsync();
// format: /sites/SITE_NAME/LIBRARY_INTERNAL_NAME/FOLDER_NAME
var folder = web.GetFolderByServerRelativeUrl(folder);
clientContext.Load( folder );
await clientContext.ExecuteQueryAsync();
var fileCreationInformation = new FileCreationInformation
{
Overwrite = true,
ContentStream = stream,
Url = fileName
};
var uploadFile= folder.Files.Add( fileCreationInformation );
clientContext.Load(uploadFile);
await clientContext.ExecuteQueryAsync();
}
catch ( Exception e )
{
Console.WriteLine(e);
throw;
}
}
Upvotes: 0