Дайте совет по перемещению видеофайла записи масштабирования из хранилища BLOB-объектов Azure в Sharepoint напрямую с помощью C#. Недавно я создал процесс, заключающийся в получении uri файла хранилища Azure -> загрузка файла на локальное устройство -> загрузка файла в Sharepoint. Однако теперь я хочу, чтобы файл Azure был загружен непосредственно в Sharepoint без необходимости предварительной загрузки файла в локальное хранилище. Как я могу этого добиться?
public async Task<Microsoft.SharePoint.Client.File> UploadFromUrl(string siteUrl, string root, string path, string filename, string originUrl)
{
using ClientContext clientContext = authManager.GetContext(siteUrl);
string text = _downloadDirectory + filename;
Folder uploadDirectory = GetUploadDirectory(clientContext, root, path);
//new WebClient().DownloadFile(new Uri(originUrl), text);
var client = new HttpClient();
GrantAccess(_downloadDirectory);
await DownloadFileTaskAsync(client, new Uri(originUrl), text);
long length = new FileInfo(text).Length;
int num = 10485760;
if (length <= num)
{
return UploadFromBuffer(clientContext, uploadDirectory, filename, text);
}
return new ChunkUploader(clientContext, num).Upload(uploadDirectory, text);
}Недавно я создал процесс, заключающийся в получении uri файла хранилища Azure -> загрузка файла на локальное устройство -> загрузка файла в Sharepoint. Однако теперь я хочу, чтобы файл Azure был загружен непосредственно в Sharepoint без необходимости предварительной загрузки файла в локальное хранилище. Как я могу этого добиться?
Обновленный прогресс: Я пытаюсь реализовать метод, предложенный ниже, следующим образом:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
namespace Binus.LMS.Course2.BackEndAPI.ZoomRecordingScheduler.ZoomRecordingHelper
{
public class GraphHandler
{
public GraphServiceClient GraphClient { get; set; }
public GraphHandler()
{
var clientId = "ad768ba0-0059-46cf-ac71-c4e627361377";
var clientSecret = "qF3r-G4~Eb3LuJgNK-7vb9ngrF43.hwG.l";
var tenantId = "3485b963-82ba-4a6f-810f-b5cc226ff898";
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, Stream fileStream)
{
try
{
var uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/items/root:/{fileName}:/content";
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 StreamContent(fileStream);
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 = "ad768ba0-0059-46cf-ac71-c4e627361377";
var clientSecret = "qF3r-G4~Eb3LuJgNK-7vb9ngrF43.hwG.l";
var tenantId = "3485b963-82ba-4a6f-810f-b5cc226ff898";
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;
}
}
}
Однако при применении GraphServiceClient возникают ошибки.
Вот содержимое моего файла .csproj:
<Project Sdk = "Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include = "AutoMapper" Version = "10.1.1" />
<PackageReference Include = "Azure.Storage.Files.Shares" Version = "12.18.0" />
<PackageReference Include = "Microsoft.Azure.Functions.Extensions" Version = "1.1.0" />
<PackageReference Include = "Microsoft.Azure.WebJobs.Extensions.DurableTask" Version = "2.6.0" />
<PackageReference Include = "Microsoft.Azure.WebJobs.Extensions.EventHubs" Version = "5.4.0" />
<PackageReference Include = "Microsoft.Azure.WebJobs.Extensions.WebPubSub" Version = "1.1.0" />
<PackageReference Include = "Microsoft.NET.Sdk.Functions" Version = "4.2.0" />
<PackageReference Include = "Microsoft.SharePoint.Client" Version = "14.0.4762.1000" />
<PackageReference Include = "Microsoft.SharePointOnline.CSOM" Version = "16.1.25012.12000" />
<PackageReference Include = "Nexus.Base.EventGridExtensions" Version = "2020.3.13.1" />
<PackageReference Include = "Nexus.Base.EventHubExtensions" Version = "2020.3.13.2" />
<PackageReference Include = "PnP.Framework" Version = "1.16.0" />
<PackageReference Include = "System.ServiceModel.Duplex" Version = "6.0.*" />
<PackageReference Include = "System.ServiceModel.Federation" Version = "6.0.*" />
<PackageReference Include = "System.ServiceModel.Http" Version = "6.0.*" />
<PackageReference Include = "System.ServiceModel.NetTcp" Version = "6.0.*" />
<PackageReference Include = "System.ServiceModel.Security" Version = "6.0.*" />
<PackageReference Include = "Zoom.API.Client.Library" Version = "2.0.4" />
</ItemGroup>
</Project>





Я хочу, чтобы файл Azure был загружен непосредственно в Sharepoint без необходимости предварительной загрузки файла в локальное хранилище. Как я могу этого добиться?
Вы можете использовать приведенный ниже код, чтобы загрузить видеофайл из хранилища BLOB-объектов Azure в общую точку без загрузки на локальный диск с помощью Azure .Net SDK.
Сначала создайте приложение Microsoft Entra ID и предоставьте разрешения API, как показано ниже:
Портал:

Код:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.Storage.Blobs;
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, Stream fileStream)
{
try
{
var uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/items/root:/{fileName}:/content";
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 StreamContent(fileStream);
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)
{
// Configuration
var connectionString = "<your azure storage connection string>";
var containerName = "your container name";
var blobName = "earth.mp4";
var handler = new GraphHandler();
var siteId = "SiteID";
var driveId = "DriveID";
var fileName = "sample.mp4";
var blobStream = await GetBlobStreamAsync(connectionString, containerName, blobName);
await handler.UploadFileToSharePoint(siteId, driveId, fileName, blobStream);
}
public static async Task<Stream> GetBlobStreamAsync(string connectionString, string containerName, string blobName)
{
var blobServiceClient = new BlobServiceClient(connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
var blobClient = containerClient.GetBlobClient(blobName);
var response = await blobClient.DownloadAsync();
return response.Value.Content;
}
}
}
Выход:
File uploaded successfully.
Ссылка: .net core — как загрузить файл и папку в библиотеку документов SharePoint с помощью Graph API на C#? - Переполнение стека от Рукмини.
Мой файл .csproj:
Project Sdk = "Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include = "Azure.Identity" Version = "1.12.0" />
<PackageReference Include = "Azure.Storage.Blobs" Version = "12.20.0" />
<PackageReference Include = "Microsoft.Graph" Version = "5.56.0" />
</ItemGroup>
</Project>
При применении метода были две ошибки. 1. невозможно преобразовать из Azure.Identity.ClientSecretCredential в Microsoft.Graph.IAuthenticationProvider 2. невозможно преобразовать из string[] в Microsoft.Graph.IHttpProvider в строке GraphClient = new GraphServiceClient(clientSecretCredential,scopes);
Отредактируйте свой вопрос и добавьте подробную информацию об ошибке.
Какие пакеты Nuget вы используете?
Удалите ненужные пакеты из приложения.
Я использовал пакет самородков api.nuget.org/v3/index.json и два частных пакета от моей компании.
Пожалуйста, поделитесь .csproj файлом.
В ответ я обновил свой файл .csproj.
Я поделился своим файлом .csproj в этом вопросе. Пожалуйста, проверьте это, спасибо.
Попробуйте мои пакеты, которые я использовал в ответе.
Хорошо, ошибки исчезли. Большое спасибо!
Рад знать, что это помогло :)