.NET幫助 MS Graph .NET(對於開發者的運行原理) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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 專案中處理 user IDs(用戶 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 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}!") $vbLabelText $csharpLabel 此代碼片段演示了如何創建一個 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 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 $vbLabelText $csharpLabel 此代碼列出用戶收件箱中前 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 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() $vbLabelText $csharpLabel 這會發送一封簡單文本正文的電子郵件。 管理日曆事件 要在用戶的日曆中添加事件: // 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 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]) $vbLabelText $csharpLabel 此代碼在日曆中安排了一個新事件。 存取 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 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 $vbLabelText $csharpLabel 此代碼會打印 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 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 $vbLabelText $csharpLabel 這會列出用戶所屬的團隊名稱。 這些功能每一個功能都展示了 MS Graph .NET 的強大和多功能性。 它們展示了如何將 Microsoft 365 服務整合到您的應用程式中。 將 MS Graph .NET 與 IronPDF 整合 如果您希望在 .NET 應用程式中處理 PDF,IronPDF 庫 是不錯的選擇。這是一個允許您的應用程式讀取、創建和操作 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. 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 $vbLabelText $csharpLabel 在此代码中需要注意的几点: 我们使用 MSGraph 来访问存储在 OneDrive 中的文件。您将需要项的 ID,您可以通过 Graph API 获得。 我們將文件流轉換為字符串以用於此示例。 这对 HTML 文档很有效。 如果您正在处理二进制文件(如 Word 文档),您可能需要使用不同的方法将这些文件转换为 PDF。 使用了 IronPDF 的 RenderHtmlAsPdf 方法从 HTML 字符串创建 PDF。 如果您的源文档不是 HTML,IronPDF 也有用於其他格式的工作方法。 记住,这只是一个简化的例子。 在真实世界的应用中,您需要更深入地处理认证,处理错误,可能需要更优雅地处理不同的文件格式。 但这可以为您在 .NET 专案中整合 MSGraph 和 IronPDF 提供一个良好的起点。 結論 对于希望将 Microsoft 365 能力整合到其 C# 应用程式中的开发者,MS Graph .NET SDK 是一个重要工具。 首先探索 MS Graph .NET SDK 授权和定价信息,起价为 $799。 常見問題解答 MS Graph .NET 如何幫助開發人員訪問 Microsoft 365 數據? MS Graph .NET 作為開發人員訪問和管理 Microsoft 365 數據的門戶,通過 Azure Active Directory 生態系統的一部分,提供簡化數據互動過程的方法。 開發人員如何在 .NET 中使用 Microsoft 365 數據生成 PDF 文檔? 開發人員可以使用 IronPDF 將 HTML 和其他文檔格式轉換為 PDF,從而在 .NET 應用程序中生成 PDF 文檔,利用通過 MS Graph .NET 訪問的數據。 開始在項目中使用 MS Graph .NET 需要什麼? 要開始使用 MS Graph .NET,您需要通過 NuGet 包管理器安裝 Microsoft.Graph 包,並設置使用客戶端憑證進行身份驗證以與 Microsoft 365 服務互動。 開發人員如何使用 MS Graph .NET 發送電子郵件? 開發人員可以通過創建帶有所需內容和接收者詳細信息的 `Message` 對象,然後利用 `GraphServiceClient` 的 `SendMail` 方法來使用 MS Graph .NET 發送電子郵件。 MS Graph .NET 可以管理 Microsoft 365 帳戶中的日曆事件嗎? 是的,MS Graph .NET 允許通過創建 `Event` 對象和使用例如 `Me.Events.Request().AddAsync(event)` 這樣的方法來添加事件到用戶的日曆中來管理日曆事件。 如何在 .NET 應用程序中將 OneDrive 文檔轉換為 PDF? 要將 OneDrive 文檔轉換為 PDF,可以使用 MS Graph .NET 獲取文檔,然後使用 IronPDF 將文檔內容轉換為 PDF 格式。 將 MS Graph .NET 與 IronPDF 整合時應考慮哪些因素? 在將 MS Graph .NET 與 IronPDF 整合時,考慮強健的身份驗證、錯誤處理以及不同文件格式的兼容性,以確保無縫轉換和數據管理。 將 MS Graph .NET 與 IronPDF 結合使用的一些實際應用是什麼? 結合使用 MS Graph .NET 和 IronPDF 可以生成 PDF 報告、將郵件存檔為 PDF,或從 Microsoft 365 數據創建標準化業務文檔。 MS Graph .NET 如何提高 .NET 應用程序的效率? MS Graph .NET 通過提供簡化的 Microsoft 365 服務訪問來提高效率,使開發人員能夠以最少的代碼檢索、管理和操作數據,從而提高生產力和應用程序的能力。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Livecharts C#(對於開發者的運行原理)C# Ref(對於開發者的運行...