|

|  How to Use Microsoft Graph API to Access SharePoint Data in C#

How to Use Microsoft Graph API to Access SharePoint Data in C#

October 31, 2024

Learn how to access SharePoint data using Microsoft Graph API in C#. Follow our step-by-step guide to effortlessly integrate and retrieve data in your applications.

How to Use Microsoft Graph API to Access SharePoint Data in C#

 

Getting Started with Microsoft Graph API in C#

 

  • Make sure you have the Microsoft Graph SDK for .NET installed. You can do this by adding the Microsoft.Graph NuGet package to your project.
  •  

  • Create an instance of the GraphServiceClient. This client is the main entry point to the Microsoft Graph API, and you'll need to authenticate it with a valid access token.

 

var graphClient = new GraphServiceClient(authProvider);

 

Authentication

 

  • Implement an authentication provider. The GraphServiceClient requires an IAuthenticationProvider to function, which handles obtaining and providing the access token.
  •  

  • You can utilize a library like Microsoft.Identity.Client (MSAL) to simplify the authentication process.

 

public class AuthProvider : IAuthenticationProvider
{
    private IPublicClientApplication _clientApp;

    public AuthProvider()
    {
        _clientApp = PublicClientApplicationBuilder.Create(clientId)
            .WithAuthority(authorityUri)
            .WithDefaultRedirectUri()
            .Build();
    }

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        var result = await _clientApp.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
            .ExecuteAsync();
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    }
}

 

Accessing SharePoint Data

 

  • To access SharePoint data, you'll refer to the GraphServiceClient to interact with SharePoint resources.
  •  

  • Use the Sites API to access a SharePoint site, and you can then navigate to lists, documents, or other resources.

 

var site = await graphClient.Sites["{site-id}"].Request().GetAsync();

 

Reading SharePoint List Items

 

  • Once you have a reference to the site, you can interact with lists, such as reading items from a list.

 

var listItems = await graphClient.Sites["{site-id}"].Lists["{list-id}"].Items.Request().GetAsync();
foreach (var item in listItems)
{
    Console.WriteLine(item.Fields.AdditionalData["Title"]);
}

 

Uploading Files to a Document Library

 

  • To upload a file, interact with the document libraries under the SharePoint site.

 

using (var stream = new FileStream("path/to/your/file.txt", FileMode.Open))
{
    await graphClient.Sites["{site-id}"]
        .Drives["{drive-id}"]
        .Root
        .ItemWithPath("DemoFolder/file.txt")
        .Content
        .Request()
        .PutAsync<DriveItem>(stream);
}

 

Handling Errors

 

  • Implement try-catch blocks to handle exceptions that may occur during API calls, which helps in capturing and responding to errors gracefully.

 

try
{
    // Your code to call the Graph API
}
catch (ServiceException ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

 

Testing & Debugging

 

  • Confirm the correct scopes and permissions in your app registration or consent process to ensure you have sufficient access to perform your desired operations on SharePoint data.
  •  

  • Make use of logging and debugging tools to ensure the requests to Microsoft Graph API are structured and authenticated correctly.

 

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now