0
votes

I am trying to download a file from SharePoint (and in a later method also upload a file to SharePoint) using a client ID and secret on a C# WinForms app. Struggling to find information on how to actually download a file or upload a file from or to a specific folder or path on SharePoint. If possible Id also like to have a progress bar to show download progress.

I am currently using async web client download elsewhere in the application from other websites, but our SharePoint server requires using secret key and client ID to connect.

string siteUrl = "https://company.sharepoint.com/sites/MediaHost";
string clientId = "clientIDhere";
string clientSecret = "secretIDhere";
using (var clientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, clientId, clientSecret))
     {
           
     }
1

1 Answers

-1
votes

As you have generated clientContext, you can reference below code to upload file to SP

private static void UploadFile()
    {
        List targetList = ctx.Web.Lists.GetByTitle("Documents");
        FileCreationInformation fci = new FileCreationInformation();
        fci.Content = System.IO.File.ReadAllBytes(@"C:\Users\mengfeik\Downloads\Dynamics.pdf");
        fci.Url = "Dynamics";
        fci.Overwrite = true;
        File fileToUpload = targetList.RootFolder.Files.Add(fci);
        ctx.Load(fileToUpload);
        ctx.ExecuteQuery();

        Console.WriteLine("upload successfully");

    }

If you want to download files in a folder, please refer to

ClientContext ctx = new ClientContext(siteUrl); ctx.Credentials = new SharePointOnlineCredentials(Username, Password);

FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(folderPath).Files;

ctx.Load(files);
ctx.ExecuteQuery();

foreach(File file in files)
{
    FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
    ctx.ExecuteQuery();

    var filePath = tempLocation + file.Name;
    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
    {
        fileInfo.Stream.CopyTo(fileStream);
    }
}

more reference doc: https://exceptionshub.com/how-to-downloadupload-files-fromto-sharepoint-2013-using-csom.html