Upload a file to Sharepoint using Microsoft Graph using C#

449 Views Asked by At

I have a client who has setup a certificate allowing me access to his Sharepoint site. He has provided me with the PDX file, ClientID, and TenantID. I believe that I’m able to authenticate with the code provided below, but I have not been successful with using the GraphServiceClient to upload a file to the site.

He has done some testing on his end with a Powershell script and he is able to upload a file through Powershell. I am not fluent in Powershell and would prefer to write my solution in C#.

I have searched high and low for examples of code to do this work. None of the examples are working. I don’t need an asynchronous solution. This process will run periodically (likely daily) to read files from one system and copy them to another. Is this possible in C# ?

Here is my code. It won't compile due to problem last line - var resultDriveItem = await...

Thanks,

public static async void TestClientCert()
    {
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var clientId = "blah";
        var tenantId = "blah";
        var clientCertificate = new X509Certificate2(@"c:\work\Test.pfx", "blah");

        var options = new ClientCertificateCredentialOptions
        {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
        };

        var clientCertCredential = new ClientCertificateCredential(
          tenantId, clientId, clientCertificate, options);

        var gc = new GraphServiceClient(clientCertCredential, scopes);

        var fileName = @"c:\work\fileToUpload\upload.doc";

        using (Stream fileStream = new FileStream(
            fileName,
            FileMode.Open,
            FileAccess.Read))
            {
            var resultDriveItem = await gc.Sites["SiteID-Blah"]
                    .Drives[0].Root.ItemWithPath(fileName).Content.Request().PutAsync<DriveItem>(fileStream);
            }
    }




2

There are 2 best solutions below

0
Elidjay Ross On

All I am saying is:

1: Connect-PnPOnline -Url "contoso.sharepoint.com" -ClientId 6c5c98c7-e05a-4a0f-bcfa-0cfc65aa1f28 -CertificatePath 'c:\mycertificate.pfx'
2: Add-PnPFile -Path c:\temp\file.pdf -Folder DocumentLibraryName

And your file is uploaded using the PnP PowerShell module (microsoft certified).

If you really wanna go with C# I would consider trying the PnP Core SDK:

// Get a reference to a folder
IFolder siteAssetsFolder = await context.Web.Folders.Where(f => f.Name == "SiteAssets").FirstOrDefaultAsync();
        
// Upload a file by adding it to the folder's files collection
IFile addedFile = await siteAssetsFolder.Files.AddAsync("test.docx", System.IO.File.OpenRead($".{Path.DirectorySeparatorChar}TestFilesFolder{Path.DirectorySeparatorChar}test.docx"));
0
RaytheonXie-MSFT On

You could refer to the following code

public static void UploadFile(ClientContext context,string uploadFolderUrl, string uploadFilePath)  
{  
    var fileCreationInfo = new FileCreationInformation  
    {  
            Content = System.IO.File.ReadAllBytes(uploadFilePath),  
            Overwrite = true,  
            Url = Path.GetFileName(uploadFilePath)  
    };  
    var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);  
    var uploadFile = targetFolder.Files.Add(fileCreationInfo);  
    context.Load(uploadFile);  
    context.ExecuteQuery();  
}  
  
using (var ctx = new ClientContext(webUri))  
{  
     ctx.Credentials = credentials;  
  
     UploadFile(ctx,"LibName/FolderName/Sub Folder Name/Sub Sub Folder Name/Sub Sub Sub Folder Name",filePath);     
}