.NET幫助 MS Graph .NET(對於開發者的運行原理) Jacob Mellor 更新:6月 22, 2025 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 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 時,設定您的 .NET 專案是第一步。以下是步驟: 1.開啟 NuGet 套件管理員。 2.搜尋 Microsoft.Graph。 3.安裝 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 根目錄中的檔案名稱。 與團隊合作 檢索使用者所屬的團隊清單: // 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,The IronPDF Library for .NET Developers 是一個可靠的選擇。這個函式庫讓您的應用程式能夠讀取、建立和處理 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 取得 ID。 本範例中,我們將檔案串流轉換為字串。 這對 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 Graph API 存取和管理 Microsoft 365 資料的閘道,而 Microsoft Graph API 是 Azure Active Directory 生態系統的一部分。它提供了簡化資料互動流程的方法。 開發人員如何使用 Microsoft 365 資料在 .NET 中產生 PDF 文件? 開發人員可利用 IronPDF for .NET 在 .NET 應用程式中產生 PDF 文件,方法是將 HTML 和其他文件格式轉換為 PDF,並利用透過 MS Graph .NET 存取的資料。 在專案中開始使用 MS Graph .NET 需要哪些條件? 若要開始使用 MS Graph .NET,您需要透過 NuGet Package Manager 安裝 Microsoft.Graph 套件,並使用用戶端憑證設定驗證以與 Microsoft 365 服務互動。 開發人員如何使用 MS Graph .NET 傳送電子郵件? 開發人員可以使用 MS Graph .NET 傳送電子郵件,方法是建立一個包含所需內容和收件者詳細資訊的 `Message` 物件,然後運用 `GraphServiceClient` 的 `SendMail` 方法。 MS Graph .NET 可以管理 Microsoft 365 帳戶中的行事曆事件嗎? 是的,MS Graph .NET 允許透過建立 `Event` 物件來管理行事曆事件,並使用 `Me.Events.Request().AddAsync(event)` 等方法將事件新增至使用者的行事曆。 如何在 .NET 應用程式中將 OneDrive 文件轉換為 PDF? 要將 OneDrive 文件轉換為 PDF,您可以使用 MS Graph .NET 抓取文件,然後運用 IronPDF for .NET 將文件內容轉換為 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 服務的簡化存取來提高效率,使開發人員能以最少的程式碼來擷取、管理和處理資料,進而提升生產力和應用程式能力。 Jacob Mellor 立即與工程團隊聊天 首席技术官 Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。 相關文章 更新12月 11, 2025 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Livecharts C#(對於開發者的運行原理)C# Ref(對於開發者的運行...
更新12月 11, 2025 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多