Featured image of post Sharepoint-Asp.net 8- Common Operations

Sharepoint-Asp.net 8- Common Operations

Collection of Code Snippets Useful for Asp.net-Sharepoint


🛠 Setting Up SharePoint Integration in ASP.NET 8

To get started, you’ll need:

  • ASP.NET 8 application
  • SharePoint Online (or On-Premises SharePoint Server)
  • Microsoft Graph API or SharePoint CSOM (Client-Side Object Model)

🔧 1. Install Required NuGet Packages

Install the required packages in your ASP.NET 8 project:

1
2
3
dotnet add package Microsoft.Graph
dotnet add package Microsoft.SharePointOnline.CSOM
dotnet add package Microsoft.Identity.Client

📂 2. Connect to SharePoint Using Microsoft Graph API

Graph API is the recommended way to interact with SharePoint Online.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
using Microsoft.Graph;
using Microsoft.Identity.Client;

var tenantId = "your-tenant-id";
var clientId = "your-client-id";
var clientSecret = "your-client-secret";

var confidentialClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clientSecret)
    .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
    .Build();

var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
{
    var authResult = await confidentialClient.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();
    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}));

📁 3. Upload a File to SharePoint

1
2
3
4
5
6
7
8
9
var siteId = "your-site-id";
var filePath = "path-to-your-file.pdf";
var fileBytes = System.IO.File.ReadAllBytes(filePath);

using var stream = new MemoryStream(fileBytes);
await graphClient.Sites[siteId].Drive.Root.ItemWithPath("Documents/sample.pdf")
    .Content
    .Request()
    .PutAsync<DriveItem>(stream);

📜 4. List Files in a SharePoint Library

1
2
3
4
5
6
var driveItems = await graphClient.Sites["your-site-id"].Drive.Root.Children.Request().GetAsync();

foreach (var item in driveItems)
{
    Console.WriteLine($"Name: {item.Name}, ID: {item.Id}");
}

🔄 5. Download a File From SharePoint

1
2
3
var fileStream = await graphClient.Sites["your-site-id"].Drive.Items["file-id"].Content.Request().GetAsync();
using var file = new FileStream("downloaded-file.pdf", FileMode.Create, FileAccess.Write);
await fileStream.CopyToAsync(file);

🏷 6. Get File Metadata

1
2
var file = await graphClient.Sites["your-site-id"].Drive.Items["file-id"].Request().GetAsync();
Console.WriteLine($"Name: {file.Name}, Last Modified: {file.LastModifiedDateTime}");

🔄 7. Create a SharePoint List Item

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var newItem = new ListItem
{
    Fields = new FieldValueSet
    {
        AdditionalData = new Dictionary<string, object>
        {
            {"Title", "New Task"},
            {"Status", "In Progress"}
        }
    }
};

await graphClient.Sites["your-site-id"].Lists["list-id"].Items.Request().AddAsync(newItem);

🗑 8. Delete a File in SharePoint

1
await graphClient.Sites["your-site-id"].Drive.Items["file-id"].Request().DeleteAsync();

🔑 9. Set Permissions on a File

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var permission = new Permission
{
    Roles = new List<string> { "read" },
    GrantedTo = new IdentitySet
    {
        User = new Identity { Id = "user-id", DisplayName = "John Doe" }
    }
};

await graphClient.Sites["your-site-id"].Drive.Items["file-id"].Permissions.Request().AddAsync(permission);

📩 10. Send a SharePoint Notification (Webhook)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var subscription = new Subscription
{
    ChangeType = "updated",
    NotificationUrl = "https://your-api.com/webhook",
    Resource = "sites/your-site-id/lists/list-id",
    ExpirationDateTime = DateTime.UtcNow.AddHours(1),
    ClientState = "your-client-state"
};

await graphClient.Subscriptions.Request().AddAsync(subscription);