|
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); |
|
} |
|
} |
|
} |
|
} |
|
} |