Skip to content

Instantly share code, notes, and snippets.

@fabienmw
Created September 25, 2024 06:50
Show Gist options
  • Save fabienmw/45d5537fbd1b3a9217fae8a6e8d0edd4 to your computer and use it in GitHub Desktop.
Save fabienmw/45d5537fbd1b3a9217fae8a6e8d0edd4 to your computer and use it in GitHub Desktop.
using PnP.Framework;
using PnP.Framework.Modernization.Publishing;
using PnP.Framework.Authentication;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
namespace SharePointFileUpload
{
class Program
{
static async Task Main(string[] args)
{
string siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite";
string libraryName = "Documents"; // The name of the document library
string filePath = @"C:\path\to\your\file.txt"; // Path to the file you want to upload
string fileName = "file.txt"; // The name you want to give the file in SharePoint
// Create the authentication manager using the client ID and secret
var clientId = "your-client-id";
var tenantId = "your-tenant-id";
var clientSecret = "your-client-secret";
// Initialize the PnP AuthenticationManager
AuthenticationManager authManager = new AuthenticationManager(clientId, tenantId, clientSecret);
// Connect to the SharePoint site
using (ClientContext context = authManager.GetContext(siteUrl))
{
try
{
// Load the web object
Web web = context.Web;
context.Load(web);
await context.ExecuteQueryAsync();
Console.WriteLine("Connected to SharePoint site: " + web.Title);
// Get the document library
List library = web.Lists.GetByTitle(libraryName);
context.Load(library.RootFolder);
await context.ExecuteQueryAsync();
// Get the target folder in the library
Folder folder = library.RootFolder;
string fileContent = File.ReadAllText(filePath);
// Upload the file
FileCreationInformation newFile = new FileCreationInformation
{
Content = System.Text.Encoding.UTF8.GetBytes(fileContent),
Url = fileName,
Overwrite = true
};
Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(newFile);
context.Load(uploadFile);
await context.ExecuteQueryAsync();
Console.WriteLine("File uploaded successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment