'How to copy a file to a sharepoint site
I have to copy a file on a sharepoint site. I have seen that the only authentication working is with the AuthenticationManager. So this works:
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(strHexagon);
Web web = ctx.Web;
User user = web.CurrentUser;
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();
lbxInfo.Items.Add(web.Title);
lbxInfo.Items.Add(user.LoginName);
Now, after having authenticated I need to copy a file to the sharepoint site. I have seen that there is ctx.Web.SaveFileToLocal but what if I have to copy from local to sharepoint?
Thanks
Solution 1:[1]
You can use the OfficeDevPnP.Core library
string str1_Url=... <--- sharepoint site
string str2_FileSource_Full= @"C:\temp\A.txt";
string str3_FileDestination_NameExt="B.txt";
string str4_TopDestination_Folder=... <--- sharepoint site title folder
string str5_TopDestination_SubFolder=... <--- folder e.g. Production
string str6_TopDestination_AllSubFolders=...<--- subfolder e.g. Test
// AuthenticationManager -> ByPasses Multi-Factor Authentication
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(str1_Url);
// Web & User definitions
Web web = ctx.Web;
User user = web.CurrentUser;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(str2_FileSource_Full);
// Rename the destination file
newFile.Url = str3_FileDestination_NameExt;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle(str4_TopDestination_Folder);
// Selects a Folder inside the root one
Microsoft.SharePoint.Client.Folder folder = docs.RootFolder.Folders.GetByUrl(str5_TopDestination_SubFolder);
folder.Folders.Add(str6_TopDestination_AllSubFolders);
var targetFolder = folder.Folders.GetByUrl(str6_TopDestination_AllSubFolders);
// Uploads a file to the targetFolder
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File uploadFile = targetFolder.Files.Add(newFile);
// Executes query
ctx.Load(docs);
ctx.Load(uploadFile);
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Patrick |