sharepoint-onlinepnp-core-sdkpnp-framework

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?


Solution

  • 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)