How to work with SharePoint files via MS Graph API in C#?

How to work with SharePoint files via MS Graph API in C#?

Microsoft Graph is your gateway to Microsoft 365 data and intelligence. It offers a unified programming model that gives you access to the vast amount of data in Microsoft 365, Windows, and Enterprise Mobility + Security. Leverage the rich data of Microsoft Graph to build organizational and consumer apps that engage millions of users. In contrast, the Microsoft Graph API provides a single endpoint, https://graph.microsoft.com, to access rich person-centric data and insights across Microsoft clouds including Microsoft 365, Windows, and Enterprise Mobility + Security. Access endpoints using REST APIs or SDKs to build apps that support Microsoft 365 scenarios spanning productivity, collaboration, education, employee and workplace intelligence, and more. Microsoft Graph also includes a powerful suite of services to manage the identity, access, compliance, and security of users and devices, protecting your organization from data leakage or loss.

What does Microsoft Graph include?

Microsoft Graph exposes REST APIs and client libraries for accessing data from the following Microsoft cloud services. People, Planner, SharePoint, Teams, To Do, Viva Insights

  • Enterprise Mobility + Security Services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune.
  • Windows Services: Activities, Devices, Notifications, Universal Print.
  • Dynamics 365 Business Central Services

  

Downloading file from SharePoint Document Library

To find files in a SharePoint document library that is already indexed. Search the element hierarchy for elements matching the query. You can search folder hierarchies, entire drives, or files shared with the current user. Search for items the user has access to. In addition to searching for items in Drive, the app allows a broader search to include items shared with the current user. To broaden your search, use the Drive resource search method.

Https Examples:

GET /users/{user-id}/drive/root/search(q='{search-text}')

GET /groups/{group-id}/drive/root/search(q='{ Search text}')

GET /me/drive/root/search(q='{search-text}')

GET /drives/{drive-id}/root/search(q='{search-text}')

GET /sites/{site-id}/drive/root/search(q='{search- text } ')

C# Code Sample:

GraphServiceClient graphClient = new GraphServiceClient( authProvider ); var stream = await graphClient.Me.Drive.Items["{driveItem-id}"].Content     .Request()     .GetAsync();

Passing "Site ID" and "Drive ID" C# Code Sample:

GraphServiceClient graphClient = new GraphServiceClient( authProvider ); var stream = await graphClient.Site["{site-id}"].Drive["{drive-id}"].Items[$"{driveItem-id}"].Content     .Request()     .GetAsync().GetAwaiter().GetResult();

Uploading files to SharePoint Document Library

The simple Upload API allows you to provide the contents of a new file or update the contents of an existing file with a single API call. It supports files that are almost 4MB in size. It helps in creating an upload session to allow your app to upload files up to the maximum file size. An upload session allows an app to upload sections of a file with successive API requests. This allows the transfer to continue even if the connection is lost while the upload is in progress.  There are two steps to uploading a file

  • Using an upload session:

This creates a temporary location where the file bytes are stored until the complete file is uploaded. After the last byte of the file has been uploaded, the upload session is complete and the final file appears in the destination folder. Alternatively, you can set the (deferCommit) property in the request arguments to defer the final creation of the file on the destination until you explicitly make a request to complete the upload.

 

  • Uploading bytes to an upload session

To upload a file or part of a file, the app makes her PUT request to the upload URL value received in the createUploadSession response. You can upload the entire file or split the file into multiple byte ranges, as long as the maximum number of bytes for any given request is less than 60 MiB. File fragments must be uploaded one by one.

C# Code Sample:

GraphServiceClient graphClient = new GraphServiceClient( authProvider ); using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(@"The contents of the file goes here.")); await graphClient.Me.Drive.Items["{driveItem-id}"].Content     .Request()     .PutAsync(stream);

Upload large file C# Code Sample:

GraphServiceClient graphClient = new GraphServiceClient( authProvider ); var uploadProps = new DriveItemUploadableProperties {   AdditionalData = new Dictionary<string, object>   {     { "@microsoft.graph.conflictBehavior", "replace" }   } }; var uploadSession = graphClient   .Drives[DriveId]   .Items[FolderId]   .ItemWithPath(FileName)   .CreateUploadSession(uploadProps)   .Request()   .PostAsync()   .GetAwaiter()   .GetResult(); var fileUploadTask = new LargeFileUploadTask(uploadSession, stream, 320 * 1024); IProgress uploadedProgress = new Progress(b=>    {       Console.WriteLine($"Uploaded {b} bytes of {stream.Length} bytes");    });    // Upload the file    var uploadResult = fileUploadTask.UploadAsync(uploadedProgress).GetAwaiter().GetResult();

 

Browse files in Document Library

A SharePoint document library is a location on a site where you can create, update, and collaborate on files with team members. Essentially, it is where you store your documents in SharePoint. Every SharePoint site has one document library when the site is created and you can create multiple document libraries on a site as well

using Microsoft.Graph; using System; using System.Threading.Tasks; namespace ConsoleApp1 {     class Program     {         static async Task Main(string[] args)         {             var graphClient = new GraphServiceClient(new Auth.DefaultAuthenticationProvider());             var driveItems = await graphClient.Sites["{site-id}"].Drives["{drive-id}"].Root.Children.Request().GetAsync();             foreach (var item in driveItems)             {                 Console.WriteLine(item.Name);             }         }     } }

About us

Do you need help in services integration? Contact us to start working for your project!

Read More

Are you looking for