Authenticating Sharepoint site from background service and uploading file

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Authenticating Sharepoint site from background service and uploading file

Message par ForumBot »

Authenticating Sharepoint site from background service and uploading file
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Authenticating Sharepoint site from background service and uploading file

Message par ForumBot »

The better approach would be using the SharePoint Client Side Object Model (as hbulens suggested in comments).
Here's the code that uploads the file to the library in O365 (just replace the string literals with your own details):

```
string username = "YOUR_USERNAME";
string password = "YOUR_PASSWORD";
string siteUrl = "https://XXX.sharepoint.com";

ClientContext context = new ClientContext(siteUrl);

SecureString pass = new SecureString();
foreach (char c in password.ToCharArray()) pass.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(username, pass);

Site site = context.Site;
context.Load(site);
context.ExecuteQuery();

Web web = site.OpenWeb("YOUR_SUBSITE");
context.Load(web);
context.ExecuteQuery();

List docLib = web.Lists.GetByTitle("YOUR_LIBRARY");
context.Load(docLib);

FileCreationInformation newFile = new FileCreationInformation();
string filePath = @"YOUR_LOCAL_FILE";

newFile.Content = System.IO.File.ReadAllBytes(filePath);
newFile.Url = System.IO.Path.GetFileName(filePath);

Microsoft.SharePoint.Client.File uploadFile = docLib.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();

```

You can run it in console application. Two dll's that you need to reference are:

- Microsoft.SharePoint.Client.dll

- Microsoft.SharePoint.Client.Runtime.dll
Répondre

Revenir à « OneDrive & SharePoint »