Esempio in C#

C#: GetContext with certificate

using Microsoft.SharePoint.Client;
using PnP.Framework;

string tenantId = "af4...5db";
string clientId = "d9d...38c";
string certPath = @".\Test20230312.pfx";
string certPassword = "aS....SF";

public ClientContext GetSPClientContext(string siteUrl)
{
    var authManager = new AuthenticationManager(clientId, certPath, certPassword, tenantId);

    ClientContext ctx = authManager.GetContext(siteUrl);
    ctx.ClientTag = "Sgart.DemoDownload";

    return ctx;
}

OpenBinaryDirect

C#: OpenBinaryDirect

string file = "https://tenantName.sharepoint.com/sites/siteName/shared documents/fileToDownload.zip";

Uri url = new Uri(file);
string siteUrl = url.GetLeftPart(UriPartial.Authority);    // => https://tenantName.sharepoint.com
var relativeUrl = url.AbsolutePath;    // => /sites/siteName/shared documents/fileToDownload.zip
if (relativeUrl.StartsWith("/sites/", StringComparison.InvariantCultureIgnoreCase))
{
    siteUrl += relativeUrl.Substring(0, relativeUrl.IndexOf('/', 8));   // => https://tenantName.sharepoint.com/sites/siteName
}


public async Task GetFileDirect()
{
    using (ClientContext ctx = GetSPClientContext(siteUrl))
    {
        var fileToDownload = ctx.Web.GetFileByServerRelativeUrl(relativeUrl);
        ctx.Load(fileToDownload);
        await ctx.ExecuteQueryAsync();

        var fileRef = fileToDownload.ServerRelativeUrl;

        // con questo da unauthorized
        using (FileStream destination = System.IO.File.Open(@"c:\temp\data2.zip", FileMode.OpenOrCreate))
        using (var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef))
        {
            fileInfo.Stream.CopyTo(destination);
        }
    }
}
The remote server returned an error: (401) Unauthorized

OpenBinaryStream

C#: ClientResult

using System.IO;

public async Task GetFileClientResult()
{
    using (ClientContext ctx = sp.GetSPClientContext(siteUrl))
    {
        var fileToDownload = ctx.Web.GetFileByServerRelativeUrl(relativeUrl);
        ctx.Load(fileToDownload);
        Microsoft.SharePoint.Client.ClientResult<Stream> mstream = fileToDownload.OpenBinaryStream();
        ctx.ExecuteQuery();

        using (FileStream destination = System.IO.File.Open(@"c:\temp\data.zip", FileMode.OpenOrCreate))
        using (StreamReader sr = new StreamReader(mstream.Value))
        {
            sr.BaseStream.CopyTo(destination);
        }
    }
}
Tags:
SharePoint 201672 PowerShell204 SharePoint 2013141 SharePoint502
Potrebbe interessarti anche: