如何使用 C# 中的 Graph API 在 SharePoint 文档库中创建文件夹、新文件夹并上传新文件夹?
我想创建一个文件夹,如果我有一个文件夹,并且该文件夹中有 5 个文件。所以我需要上传包含所有 5 个文件的文件夹。
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# Sharp 在 SharePoint 上创建文件夹,您可以按照以下文档操作:
要将多个文件上传到文件夹,请使用以下方法:
public async Task<DriveItem> UploadFilesAsync(string siteId, string libraryId, string folderPath, string fileName, Stream fileStream)
{
string path = $":/{folderPath}/{fileName}:/content";
try
{
return await GraphClient.Sites[siteId].Drives[libraryId].Root.ItemWithPath(path).Content.Request().PutAsync<DriveItem>(fileStream);
}
catch (ServiceException ex)
{
Console.WriteLine($"Error uploading file: {ex.Message}");
return null;
}
}
上传文件夹:
public async Task UploadFolderAsync(string siteId, string libraryId, string localFolderPath, string remoteFolderPath)
{
DirectoryInfo dirInfo = new DirectoryInfo(localFolderPath);
foreach (var file in dirInfo.GetFiles())
{
using (var stream = new FileStream(file.FullName, FileMode.Open))
{
await UploadFileToFolderAsync(siteId, libraryId, remoteFolderPath, file.Name, stream);
}
}
}
您可以在代码中使用这些方法,例如:await graphHandler.CreateFolderAsync("site-id", "root", "NewFolder");。确保您已分配权限,例如 azure 上的
Files.ReadWrite.All
、Sites.ReadWrite.All
。