D. Kelly
D. Kelly

Reputation: 1

Upload a file to Sharepoint using Microsoft Graph using C#

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...

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);
    }
}

Upvotes: 0

Views: 1281

Answers (2)

user2895734
user2895734

Reputation: 1

Instead of

.ItemWithPath(fileName) -- Path

Use

.ItemWithPath("TestFile.txt")

Upvotes: 0

Elidjay Ross
Elidjay Ross

Reputation: 51

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"));

Upvotes: 0

Related Questions