
MS Graph .NET(對於開發者的運行原理)
MS Graph .NET 是一個存取資料的工具,用於與 Microsoft Graph API 進行交互,這是 Azure Active Directory (Azure AD) 生態系統的核心部分。 Microsoft Graph 是進入 Microsoft 365 中資料和智能的入口。它允許開發人員存取、管理和分析跨各種 Microsoft 服務的資料。 Microsoft Graph 客戶端程式庫通過提供一組易於與 API 交互的方法來簡化此過程。
IronPDF 是一個用於在 .NET 應用程式中生成 PDF 文件的程式庫。 它將 HTML 轉換為 PDF,使其在自動建立報告、發票和文件方面非常有用。 IronPDF 與 .NET 應用程式相容,提供了一種簡單的 PDF 生成方法。
結合 MS Graph .NET 和 IronPDF,允許開發人員建立能夠操作 Microsoft 365 資料並生成 PDF 文件的應用程式。 此組合對於開發需要從 Microsoft 服務中獲取資料並需以標準文件格式呈現資料的商業應用程式非常強大。
開始使用 MS Graph .NET
在 .NET 項目中設置 MS Graph .NET
要有效使用 MS Graph .NET,特別是在 .NET Core 項目中處理使用者 ID,第一步是設置您的 .NET 項目。以下是步驟:
- 打開 NuGet 套件管理器。
- 搜索 Microsoft.Graph。
- 安裝 Microsoft.Graph 套件。

此過程將 MS Graph .NET 新增到您的項目中。 現在,您可以開始使用它編寫程式碼。
一個基本的程式碼範例
假設您想檢索當前使用者的個人資料資訊。 以下是一個簡單的程式碼範例:
// Required namespaces
using Azure.Identity;
using Microsoft.Graph;
// Defining necessary credentials and scope
var clientId = "Your_Application_Id";
var tenantId = "Your_Tenant_Id";
var clientSecret = "Your_Client_Secret";
var scopes = new[] { "User.Read" };
// Configuring TokenCredentialOptions for Azure Public Cloud
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// Authenticating using client credentials
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
// Creating a new instance of GraphServiceClient
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
// Fetching current user's profile information
var user = await graphClient.Me
.Request()
.GetAsync();
// Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!");' Required namespaces
Imports Azure.Identity
Imports Microsoft.Graph
' Defining necessary credentials and scope
Private clientId = "Your_Application_Id"
Private tenantId = "Your_Tenant_Id"
Private clientSecret = "Your_Client_Secret"
Private scopes = { "User.Read" }
' Configuring TokenCredentialOptions for Azure Public Cloud
Private options = New TokenCredentialOptions With {.AuthorityHost = AzureAuthorityHosts.AzurePublicCloud}
' Authenticating using client credentials
Private clientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)
' Creating a new instance of GraphServiceClient
Private graphClient = New GraphServiceClient(clientSecretCredential, scopes)
' Fetching current user's profile information
Private user = await graphClient.Me.Request().GetAsync()
' Printing user's display name
Console.WriteLine($"Hello, {user.DisplayName}!")此程式碼片段演示了建立一個新的 GraphServiceClient 實例,使用客戶端秘密進行 Azure AD 驗證。 它使用客戶端憑證進行身份驗證。 然後,它檢索當前使用者的顯示名稱。 繼此之後,確保 MS Graph .NET 以及您的身份驗證提供程式配置已新增到您的項目中。
MS Graph .NET 的功能
檢索使用者電子郵件
要從使用者的 Microsoft 帳戶郵箱中檢索電子郵件,您需要使用 Mail.Read 權限。 以下是如何列出最新郵件的方法:
// Retrieving the top 10 messages from the user's mailbox
var messages = await graphClient.Me.Messages
.Request()
.Top(10)
.GetAsync();
// Iterating through the messages and printing their subjects
foreach (var message in messages)
{
Console.WriteLine($"Subject: {message.Subject}");
}' Retrieving the top 10 messages from the user's mailbox
Dim messages = Await graphClient.Me.Messages.Request().Top(10).GetAsync()
' Iterating through the messages and printing their subjects
For Each message In messages
Console.WriteLine($"Subject: {message.Subject}")
Next message此程式碼列出使用者收件箱中的前 10 封電子郵件的主題。
發送電子郵件
發送電子郵件涉及建立一個 Message 物件並發送它:
// Creating a message to be sent
var message = new Message
{
Subject = "Hello from MS Graph .NET",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "Hello, this is a test email."
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "recipient@example.com"
}
}
}
};
// Sending the email
await graphClient.Me.SendMail(message, null)
.Request()
.PostAsync();' Creating a message to be sent
Dim message As New Message With {
.Subject = "Hello from MS Graph .NET",
.Body = New ItemBody With {
.ContentType = BodyType.Text,
.Content = "Hello, this is a test email."
},
.ToRecipients = New List(Of Recipient)() From {
New Recipient With {
.EmailAddress = New EmailAddress With {.Address = "recipient@example.com"}
}
}
}
' Sending the email
Await graphClient.Me.SendMail(message, Nothing).Request().PostAsync()此程式碼發送一封包含簡單文字正文的電子郵件。
管理日曆事件
要向使用者的日曆中新增事件:
// Creating a calendar event
var @event = new Event
{
Subject = "Team Meeting",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Discuss project updates."
},
Start = new DateTimeTimeZone
{
DateTime = "2024-04-15T12:00:00",
TimeZone = "Pacific Standard Time"
},
End = new DateTimeTimeZone
{
DateTime = "2024-04-15T14:00:00",
TimeZone = "Pacific Standard Time"
},
Location = new Location
{
DisplayName = "Conference Room 1"
}
};
// Adding the event to the user's calendar
await graphClient.Me.Events
.Request()
.AddAsync(@event);' Creating a calendar event
Dim [event] As [Event] = New [Event] With {
.Subject = "Team Meeting",
.Body = New ItemBody With {
.ContentType = BodyType.Html,
.Content = "Discuss project updates."
},
.Start = New DateTimeTimeZone With {
.DateTime = "2024-04-15T12:00:00",
.TimeZone = "Pacific Standard Time"
},
.End = New DateTimeTimeZone With {
.DateTime = "2024-04-15T14:00:00",
.TimeZone = "Pacific Standard Time"
},
.Location = New Location With {.DisplayName = "Conference Room 1"}
}
' Adding the event to the user's calendar
Await graphClient.Me.Events.Request().AddAsync([event])此程式碼在日曆中安排了一個新事件。
存取 OneDrive 文件
要列出使用者 OneDrive 根目錄中的文件:
// Retrieving files from the root OneDrive folder
var files = await graphClient.Me.Drive.Root.Children
.Request()
.GetAsync();
// Printing each file's name
foreach (var file in files)
{
Console.WriteLine(file.Name);
}' Retrieving files from the root OneDrive folder
Dim files = Await graphClient.Me.Drive.Root.Children.Request().GetAsync()
' Printing each file's name
For Each file In files
Console.WriteLine(file.Name)
Next file此程式碼列印 OneDrive 根目錄中的文件名稱。
使用 Teams
要檢索使用者所屬的團隊列表:
// Retrieving teams that the user is part of
var teams = await graphClient.Me.JoinedTeams
.Request()
.GetAsync();
// Printing each team's display name
foreach (var team in teams)
{
Console.WriteLine($"Team name: {team.DisplayName}");
}' Retrieving teams that the user is part of
Dim teams = Await graphClient.Me.JoinedTeams.Request().GetAsync()
' Printing each team's display name
For Each team In teams
Console.WriteLine($"Team name: {team.DisplayName}")
Next team此程式碼列出使用者所屬的 Teams 名稱。
這些功能展示了 MS Graph .NET 的強大和多樣性。 它們展示瞭如何將 Microsoft 365 服務整合到您的應用程式中。
將 MS Graph .NET 與 IronPDF 整合

如果您正在尋找在 .NET 應用程式中使用 PDF 的方法,IronPDF 程式庫對於 .NET 開發人員來說是不錯的選擇。它是一個程式庫,使您的應用程式能夠讀取、建立和操作 PDF 文件,而無需使用任何其他外部 PDF 工具或軟體。
使用案例:將 IronPDF 與 MS Graph .NET 合併
想像一下,您正在構建一個需要從 Microsoft 365 獲取文件的應用程式,比如報告或發票,並將它們轉換為 PDF。 MS Graph .NET 允許您與 Microsoft 365 資源互動,包括儲存在 OneDrive 或 SharePoint 中的文件。 然後可以使用 IronPDF 將這些文件轉換為 PDF。 此組合對於自動報告生成或將電子郵件和附件存檔為便於分發的 PDF 格式特別有用。
程式碼範例:從 MS Graph 到 PDF
讓我們看看一個簡單的例子。 我們將使用 MS Graph .NET 從 OneDrive 獲取文件,然後使用 IronPDF 將該文件轉換為 PDF。 我假設您已經設置了 MSGraph 的身份驗證; 如果沒有,Microsoft 的網站上有大量文件可以幫助您入門。
// Simplified example, ensure to handle exceptions and errors appropriately.
using Microsoft.Graph;
using IronPdf;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Setting up the GraphServiceClient with a DelegateAuthenticationProvider
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
// Insert code to acquire token
string accessToken = await GetAccessTokenAsync();
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
}));
// Replace 'itemId' with the ID of your document in OneDrive
var stream = await graphClient.Me.Drive.Items["itemId"].Content.Request().GetAsync();
// IronPDF setup to convert the fetched file to PDF
var renderer = new HtmlToPdf();
var pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream));
// Save the PDF to a file
pdfDocument.SaveAs("YourDocument.pdf");
}
// Method to convert a Stream to a String
static string StreamToString(Stream stream)
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
// Method to obtain the access token
static async Task<string> GetAccessTokenAsync()
{
// Implement your authentication logic here to return the access token
return "your_access_token";
}
}' Simplified example, ensure to handle exceptions and errors appropriately.
Imports Microsoft.Graph
Imports IronPdf
Imports System.IO
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Setting up the GraphServiceClient with a DelegateAuthenticationProvider
Dim graphClient = New GraphServiceClient(New DelegateAuthenticationProvider(Async Sub(requestMessage)
' Insert code to acquire token
Dim accessToken As String = Await GetAccessTokenAsync()
requestMessage.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken)
End Sub))
' Replace 'itemId' with the ID of your document in OneDrive
Dim stream = Await graphClient.Me.Drive.Items("itemId").Content.Request().GetAsync()
' IronPDF setup to convert the fetched file to PDF
Dim renderer = New HtmlToPdf()
Dim pdfDocument = renderer.RenderHtmlAsPdf(StreamToString(stream))
' Save the PDF to a file
pdfDocument.SaveAs("YourDocument.pdf")
End Function
' Method to convert a Stream to a String
Private Shared Function StreamToString(ByVal stream As Stream) As String
Using reader = New StreamReader(stream)
Return reader.ReadToEnd()
End Using
End Function
' Method to obtain the access token
Private Shared Async Function GetAccessTokenAsync() As Task(Of String)
' Implement your authentication logic here to return the access token
Return "your_access_token"
End Function
End Class該程式碼中有幾點需要注意:
- 我們正在使用 MSGraph 存取儲存在 OneDrive 中的文件。您需要獲取項目的 ID,這可以通過 Graph API 獲得。
- 在本範例中,我們將文件流轉換為字串。 這對 HTML 文件效果很好。 如果您在處理二進位文件(如 Word 文件),您將需要使用不同的方法將這些文件轉換為 PDF。
- 此處使用 IronPDF 的 RenderHtmlAsPdf 方法來從 HTML 字串建立 PDF。 如果您的源文件不是 HTML,IronPDF 也提供了處理其他格式的方法。
請記住,這是一個簡化的範例。 在實際應用程式中,您需要更穩健地處理身份驗證,管理錯誤,並可能更優雅地處理不同的文件格式。 但這應該給您提供一個在 .NET 項目中整合 MSGraph 和 IronPDF 的良好起點。
結論

對於希望將 Microsoft 365 功能整合到其 C# 應用程式中的開發人員而言,MS Graph .NET SDK 是一個不可或缺的工具。 從 $999 開始探索 MS Graph .NET SDK 授權和定價資訊。

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.
Related Articles


