How to Upload a File to a Document Library in Sharepoint

How to upload files to sharepoint online document library using c#

Asked and answered:
https://sharepoint.stackexchange.com/questions/171184/upload-a-folder-with-sub-folders-and-files-recursively-with-pure-csom

Here's an example of one that was already written:

public class FileHelper
{
public static void UploadDocument(ClientContext clientContext, string sourceFilePath, string serverRelativeDestinationPath)
{
using (var fs = new FileStream(sourceFilePath, FileMode.Open))
{
var fi = new FileInfo(sourceFilePath);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, serverRelativeDestinationPath , fs, true);
}
}

public static void UploadFolder(ClientContext clientContext, System.IO.DirectoryInfo folderInfo, Folder folder)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;

try
{
files = folderInfo.GetFiles("*.*");
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
}

catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}

if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
Console.WriteLine(fi.FullName);
clientContext.Load(folder);
clientContext.ExecuteQuery();
UploadDocument(clientContext, fi.FullName, folder.ServerRelativeUrl + "/" + fi.Name);
}

subDirs = folderInfo.GetDirectories();

foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
Folder subFolder = folder.Folders.Add(dirInfo.Name);
clientContext.ExecuteQuery();
UploadFolder(clientContext, dirInfo, subFolder);
}
}
}

public static void UploadFoldersRecursively(ClientContext clientContext, string sourceFolder, string destinationLigraryTitle)
{
Web web = clientContext.Web;
var query = clientContext.LoadQuery(web.Lists.Where(p => p.Title == destinationLigraryTitle));
clientContext.ExecuteQuery();
List documentsLibrary = query.FirstOrDefault();
var folder = documentsLibrary.RootFolder;
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sourceFolder);

clientContext.Load(documentsLibrary.RootFolder);
clientContext.ExecuteQuery();

folder = documentsLibrary.RootFolder.Folders.Add(di.Name);
clientContext.ExecuteQuery();

FileHelper.UploadFolder(clientContext, di, folder);
}
}

To use it

FileHelper.UploadFoldersRecursively(clientContext, @"C:\BigFolder", "Documents");

How do you upload a file to a document library in sharepoint?

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);

SPFolder myLibrary = oWeb.Folders[documentLibraryName];

// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);

// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

// Commit
myLibrary.Update();
}
}

How can i upload a file into Sharepoint library, in ASP.NET MVC?

You can use SharePoint CSOM to create folder:

            string userName = "user@Tenant.onmicrosoft.com";
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();
}

Sample Image

Create Folder in SharePoint using CSOM

Then upload file to the new created folder:

            string userName = "user@Tenant.onmicrosoft.com";
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");
}

Sample Image

How to upload a file to a SharePoint library folder using the Microsoft Graph API C# SDK?

This is how I did it in the end:

try
{
using var stream = new MemoryStream(contentBytes);

// Retrieve the folder item.
var items = await this._graphClient.Sites["siteId"].Lists["listId"].Items
.Request()
.GetAsync();

// I happened to know the folder name in advance, so that is what I used to retrieve the folder item from Items collection.
// I could not find how to query the Graph to get just the folder instead of all the items. Hopefully I will find it and update the code.
var folderItem = items.FirstOrDefault(i => i.WebUrl.Contains($"{path}") && i.ContentType.Name == "Folder");

// you must create a DriveItem, not a ListItem object. It is important to set the the File property.
var listItem = new DriveItem
{
Name = fileName,
File = new Microsoft.Graph.File(),
AdditionalData = new Dictionary<string, object>()
{
{ "@microsoft.graph.conflictBehavior", "replace" }
},

};

listItem = await this._graphClient.Sites["siteId"].Lists["listId"].Items[folderItem.Id].DriveItem.Children
.Request()
.AddAsync(listItem);

// I needed the drive Id here. it is in the Drives properties of the site. It corresponds to the drive associated to the library.
var uploadSession = await this._graphClient.Sites["siteId"].Drives["driveId"]
.Items[listItem.Id]
.CreateUploadSession()
.Request()
.PostAsync();

var largeFileUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, stream);

UploadResult<DriveItem> uploadResult = await largeFileUploadTask.UploadAsync();

return uploadResult;
}
catch (ServiceException e)
{
Log.Error(e);
throw;
}

It is important to know that first you need to retrieve the drive ID associated to the library when creating the upload session. The drive can be retrieved from the site object, provided you load the expanded drives query option.

var siteQueryOptions = new List<QueryOption>()
{
new QueryOption("expand", "drives")
};

var site = await this._graphClient.Sites.GetByPath(siteRelativeUrl, hostName)
.Request(siteQueryOptions)
.GetAsync();

string driveId = site.Drives.FirstOrDefault(d => d.WebUrl.EndsWith(workingDocumentsLibName, StringComparison.InvariantCultureIgnoreCase))?.Id;

Upload file to Sharepoint document library together with all properties

You have to do them separately and it doesn't actually create a copy of the file. SharePoint stores the deltas and in your case, there wouldn't be a change in the document. When you look at the version history, it can be misleading b/c you will see version 1.0 is 4GB and version 2.0 is 4GB which would make you think that you are consuming 8GB but that is not the case. If you were add a 3rd version that was 5GB, you wouldn't have 13GB used. Instead, the database will only store 5GB of data and SharePoint essentially pieces together the file from the database.

SPO & CSOM & Can't upload a document to a document library, but I can create a folder

I found out the problem. The issue was the call ctx.Load(docs.RootFolder.Folders); I had removed this piece of code, I was now able to upload documents.

Upload/Create file in SharePoint Online Document Library using MS Graph

In postman, we could upload the file like this:

choose binary in the Body:

Sample Image



Related Topics



Leave a reply



Submit