.net – How to upload files from a Visual Studio C# console app to Sharepoint?


I’m pretty new to this (4 months into my first dev job) and I’m stuck on something that should probably be simple but I can’t figure it out.

The company asked me to write a C# program that uploads files from my computer to SharePoint Online. I googled around and found some code examples that use SharePointOnlineCredentials.

here’s what I have:

using Microsoft.SharePoint.Client;

using System;
using System.IO;

    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "https://company.sharepoint.com/sites/mysite";
            string username = "[email protected]";
            string password = "MyPassword!";
            
            var securePassword = new System.Security.SecureString();
            foreach (char c in password)
                securePassword.AppendChar(c);
                
            var credentials = new SharePointOnlineCredentials(username, securePassword);
            
            using (var ctx = new ClientContext(siteUrl))
            {
                ctx.Credentials = credentials;
                var list = ctx.Web.Lists.GetByTitle("Documents");
                ctx.Load(list.RootFolder);
                ctx.ExecuteQuery();  // <- fails here
                
                string filePath = @"C:\test.txt";
                using (var fs = new FileStream(filePath, FileMode.Open))
                {
                    var fi = new FileInfo(filePath);
                    var fileUrl = $"{list.RootFolder.ServerRelativeUrl}/{fi.Name}";
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, fileUrl, fs, true);
                }
            }
        }
    }

The weird thing is:

If I put wrong username/password → I get the error I expect (sign-in name doesn’t match)

If I put wrong URL → I get “can’t resolve remote name”

But when EVERYTHING is correct → this error:

Microsoft.SharePoint.Client.IdcrlException: ‘Identity Client Runtime Library (IDCRL)
did not get a response from the Login server.’

I’ve been stuck on this for hours. I found some old posts mentioning “legacy authentication” but most are from 2021 or older. Then I saw something about PnP Framework and Azure AD apps but honestly I’m kind of lost.

I tried installing PnP.Framework from NuGet and using AuthenticationManager but that also gave me errors about needing tokens or parameters or something.

So my questions:

  1. Does SharePointOnlineCredentials just not work anymore? Like at all?
  2. If I need Azure AD, what exactly do I need to set up? (I can access our Azure portal but I don’t want to break anything)
  3. Is there a simpler way for someone who’s just starting out?

Using Visual Studio 2022, .NET Framework 4.8, and Microsoft.SharePointOnline.CSOM package.

Leave a Reply

Your email address will not be published. Required fields are marked *