Muflix
Muflix

Reputation: 6798

Upload file to the SharePoint site with Azure App credentials

I have

and these variables

I need to upload a document to the SharePoint Site Folder.

I tried to use PnP Core SDK but I am not able to configure the Authentication, it seems that there is no authentication provider to just accept plain password (UsernamePasswordAuthenticationProvider does not accept name of the application as a username).

Overall the PnP Core SDK is adding a lot of complexity to my console application because it depends on Microsoft.Extensions.Hosting.Host.

is there a way how to authenticate via PnP or should I use REST API directly?

Alternatively the PnP Framework that will be deprecated (if I understand the documentation correctly) can authenticate towards Azure Application, but this is only documentation I found.

Any idea or recommendation?

Update

When I try this (PnP Framework)

using Microsoft.SharePoint.Client;
using PnP.Core.Model.SharePoint;
using PnP.Framework;

ClientContext context =
                new AuthenticationManager()
                    .GetACSAppOnlyContext(
                        siteUrl: "siteUrl",
                        appId: "clientId",
                        appSecret: "password");
    
IFolder? folder = (IFolder?)context.Web.Folders.Where(f => f.Name == directory).FirstOrDefault();

if (folder == null) throw new Exception("Folder not found.");

folder.Files.Add(filename, content, overwrite);

I am getting this exception

Microsoft.SharePoint.Client.CollectionNotInitializedException: 'The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'

Any Idea how to explicitly request the collection?

Upvotes: 1

Views: 2389

Answers (2)

Muflix
Muflix

Reputation: 6798

Create ClientContext

using Microsoft.SharePoint.Client;
using PnP.Framework;

ClientContext _context =
                new AuthenticationManager()
                    .GetACSAppOnlyContext(
                        siteUrl: siteUrl,
                        appId: appId,
                        appSecret: appSecret);

Method for uploading the file

public void UploadFile(Stream stream, string listTitle, string directory, string filename, bool overwrite)
{
      List list = _context.Web.Lists.GetByTitle(listTitle);
      var url = Path.Combine(directory, filename);
      var file = new FileCreationInformation() { ContentStream = stream, Overwrite = overwrite, Url = url };
      var addedFile = list.RootFolder.Files.Add(file);
      _context.Load(addedFile);
      _context.ExecuteQuery();
}

Call example

UploadFile(stream, "Documents", "Shared Documents/FooSubFolder/", "filename.txt", true)

Upvotes: 0

Zella_msft
Zella_msft

Reputation: 372

According to my research and testing, if you want to connect to SharePoint Online with Azure App credentials, you can use the following code, and then upload file to SharePoint:

string siteUrl = "https://contoso.sharepoint.com/sites/demo";
using (var cc = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, "[Your Client ID]", "[Your Client Secret]"))
{
    cc.Load(cc.Web, p => p.Title);
    cc.ExecuteQuery();
    Console.WriteLine(cc.Web.Title);
};

Here is a document about upload file to SharePoint, you can refer to the code in this document: Upload a document to a SharePoint list from Client Side Object Model

Also, you can try to install Microsoft.SharePointOnline.CSOM to fix the error:

Microsoft.SharePoint.Client.CollectionNotInitializedException: 'The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'

More information for reference: Granting access using SharePoint App-Only

Upvotes: 1

Related Questions