如何使用 C# 中的 Graph API 上传 SharePoint 文档库中的文件和文件夹?

问题描述 投票:0回答:1

我已经在Azure Portal中完成了应用程序注册,并且我有一个tenantId,ClientId和clientSecret。

我想在 C# 中使用 Microsoft.Graph SDK 上传文件。

我必须使用文件路径和文档库名称上传文件。

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Sites.GetAllSites;

namespace UploadFiles;
public class GraphHandler
{
    public GraphServiceClient GraphClient { get; set; }

    public GraphHandler(string tenantId, string clientId, string clienSecret)
    {
        GraphClient = CreateGraphClient(tenantId, clientId, clienSecret);
    }

    public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
    {
        var option = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };

        var clientSecretCredentials = new ClientSecretCredential(tenantId, clientId, clientSecret, option);
        var scope = new[] { "https://graph.microsoft.com/.default" };

        return new GraphServiceClient(clientSecretCredentials, scope);
    }
}

我想使用这个图形处理程序。

这怎么可能?

c# .net-core azure-active-directory azure-web-app-service
1个回答
0
投票

创建一个 Microsoft Entra ID 应用程序并授予 API 权限,如下所示:

enter image description here

要将文件上传到 SharePoint 文档库,请使用以下代码:

using System.Net.Http.Headers;
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;

namespace UserProperties
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            var tenantId = "TenantID";

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            GraphClient = new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task UploadFileToSharePoint(string siteId, string driveId, string fileName, string filePath)
        {
            try
            {
                var uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/items/root:/{fileName}:/content";
                byte[] fileBytes = File.ReadAllBytes(filePath);
                using (var httpClient = new HttpClient())
                {
                    var accessToken = await GetAccessTokenAsync();
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    using (var httpRequest = new HttpRequestMessage(HttpMethod.Put, uploadUrl))
                    {
                        httpRequest.Content = new ByteArrayContent(fileBytes);
                        httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        using (var response = await httpClient.SendAsync(httpRequest))
                        {
                            response.EnsureSuccessStatusCode();
                            Console.WriteLine("File uploaded successfully.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error uploading file: {ex.Message}");
            }
        }

        private async Task<string> GetAccessTokenAsync()
        {
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            var tenantId = "TenantID";

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var tokenRequestContext = new TokenRequestContext(new string[] { "https://graph.microsoft.com/.default" });

            var accessTokenResult = await clientSecretCredential.GetTokenAsync(tokenRequestContext);

            return accessTokenResult.Token;
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var handler = new GraphHandler();
            var siteId = "SiteID"; 
            var driveId = "DriveID"; 
            var fileName = "rukk.txt"; 
            var filePath = "C:/Users/rukmini/Downloads/rukk.txt"; 
            await handler.UploadFileToSharePoint(siteId, driveId, fileName, filePath);
        }
    }
}

文件上传成功:

enter image description here

enter image description here

要获取站点的站点 ID,请使用以下查询:

https://graph.microsoft.com/v1.0/sites?search=testrukk

enter image description here

要获取驱动器 ID(文档库 ID),请使用以下查询:

https://graph.microsoft.com/v1.0/sites/SiteID/drives

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.