Reputation: 216
i have read a lot of questions about this but i am stil confused.. I made a powerapps project where i uploaded a file into sharepoint, that upload would create a folder with a text field that would be fullfilled in that form.. And inside the fields would be uploaded, if the the name was already a folder, he would just upload into the library!
Now what i want, is to do the exact same thing, but with C# ASP.NET, i want to create a form where i send 2 values, a text to create the folder and the file to be uploaded into that folder! Can anyone please help? :) thanks for any help ! :)
Upvotes: 1
Views: 7275
Reputation: 3615
You can use SharePoint CSOM to create folder:
string userName = "[email protected]";
string Password = "*********";
var securePassword = new SecureString();
foreach (char c in Password)
{
securePassword.AppendChar(c);
}
using (var ctx = new ClientContext("https://tenant.sharepoint.com/sites/sitename"))
{
ctx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(userName, securePassword);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List byTitle = ctx.Web.Lists.GetByTitle("LibraryName");
// New object of "ListItemCreationInformation" class
ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();
// Below are options.
// (1) File - This will create a file in the list or document library
// (2) Folder - This will create a foder in list(if folder creation is enabled) or documnt library
listItemCreationInformation.UnderlyingObjectType = FileSystemObjectType.Folder;
// This will et the internal name/path of the file/folder
listItemCreationInformation.LeafName = "NewFolderFromCSOM";
ListItem listItem = byTitle.AddItem(listItemCreationInformation);
// Set folder Name
listItem["Title"] = "NewFolderFromCSOM";
listItem.Update();
ctx.ExecuteQuery();
}
Create Folder in SharePoint using CSOM
Then upload file to the new created folder:
string userName = "[email protected]";
string Password = "*******";
var securePassword = new SecureString();
foreach (char c in Password)
{
securePassword.AppendChar(c);
}
using (var ctx = new ClientContext("https://tenant.sharepoint.com/"))
{
ctx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(userName, securePassword);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes("D:\\document.pdf");
newFile.Url = @"document.pdf";
List byTitle = ctx.Web.Lists.GetByTitle("Documents");
Folder folder = byTitle.RootFolder.Folders.GetByUrl("NewFolderFromCSOM");
ctx.Load(folder);
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(newFile);
uploadFile.CheckIn("checkin", CheckinType.MajorCheckIn);
ctx.Load(byTitle);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
Console.WriteLine("done");
}
Upvotes: 3