sharepoint-onlinemicrosoft-graph-sdks

How can I upload a new version of a file to a SharePoint document library using the Graph SDK?


I'm using the MS Graph SDK to upload some documents to our corporate SharePoint site. I can upload a document just fine using syntax like:

var driveItem = graphClient.Drives[*driveId*].Root.ItemWithPath(*file.Name*).Content.PutAsync(*stream*).Result;

I can use the same method to replace the file with a new file, but my requirement is not to overwrite the file that's already there, but instead to upload a new version.

First, I tried replacing the post operation I used for the initial file with a patch operation:

var driveItem =  graphClient.Drives[*driveId*].Root.ItemWithPath(*file.Name*).Content.PatchAsync(*stream*).Result;

....the patch operation just isn't available at this endpoint.

So I tried creating a requestBody to capture the change (content only, no metadata change!):

var requestBody = new DriveItem
    {
        Content = *file*
    };
var driveItem = graphClient.Drives[*driveId*].Items[*driveItemId*].PatchAsync(requestBody).Result;

This also fails.

How can I upload a new version of a file to a SharePoint library using the Graph SDK?


Solution

  • This worked for me. The itemId used in the second call is the Id of the file created in the first call.

    private async static Task UploadFile()
    {
        var authenticationProvider = new BaseBearerTokenAuthenticationProvider(new TokenProvider());
        var graphServiceClient = new GraphServiceClient(authenticationProvider);
    
        var response = await graphServiceClient
            .Drives["b!cQAGne73X02RW5qyDPL4skiS-tT2Lw1JmPAws8_FHnp8cknSG44lRZZUH3XKqrWN"]
            .Root
            .ItemWithPath("Hello World.txt")
            .Content
            .PutAsync(new MemoryStream(Encoding.UTF8.GetBytes("Hello World")));
    
        Console.WriteLine("File uploaded");
    }
    
    private async static Task UpdateFile()
    {
        var authenticationProvider = new BaseBearerTokenAuthenticationProvider(new TokenProvider());
        var graphServiceClient = new GraphServiceClient(authenticationProvider);
    
        var response = await graphServiceClient
            .Drives["b!cQAGne73X02RW5qyDPL4skiS-tT2Lw1JmPAws8_FHnp8cknSG44lRZZUH3XKqrWN"]
            .Items["01GGRIK46VMB4YFUDQIFHL3QGCPYK4IRQ6"]
            .Content
            .PutAsync(new MemoryStream(Encoding.UTF8.GetBytes("Hello World (revised)")));
    
        Console.WriteLine("File updated");
    }
    

    enter image description here