https://learn.microsoft.com/en-us/information-protection/develop/quick-app-initialization-csharp
Introduction
In today's data-driven world, protecting sensitive information is paramount. Microsoft Information Protection (MIP) provides robust capabilities for classifying, labeling, and protecting documents across your organization. While many solutions focus on applying and modifying sensitivity labels, there's often a need for read-only operations—such as auditing, compliance checking, or simply understanding what labels are applied to existing documents.
In this article, we'll explore how to build a simple yet powerful C# console application that reads Microsoft Information Protection sensitivity labels from files without modifying them. This solution is perfect for compliance officers, IT administrators, or developers who need to audit document classifications safely.
What We'll Build
Our application will:
- Connect to Microsoft Information Protection services
- List all available sensitivity labels in your organization
- Read existing sensitivity labels from specific files
- Display detailed label information including protection status
- Operate in read-only mode, ensuring no modifications to files
Prerequisites
Before we start, ensure you have:
- Azure AD App Registration with appropriate MIP permissions
- Visual Studio or .NET Framework 4.8 development environment
- Microsoft Information Protection SDK (via NuGet)
- Microsoft Authentication Library (MSAL) for authentication
- Files with sensitivity labels applied for testing
Azure AD App Registration Setup
First, you'll need to register an application in Azure Active Directory:
- Navigate to the Azure Portal → Azure Active Directory → App registrations
- Click "New registration"
- Provide a name (e.g., "Sensitivity Label Reader")
- Set redirect URI to
http://localhost
(for desktop app) - Under API permissions, add:
UnifiedPolicy.User.Read
(for reading label policies)InformationProtectionPolicy.Read
(for accessing protection policies)
Project Setup and Dependencies
Create a new console application and install the required NuGet packages:
<PackageReference Include="Microsoft.InformationProtection.File" Version="1.17.158" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.76.0" />
The Complete Implementation
Here's our streamlined, single-file implementation:
using Microsoft.InformationProtection;using Microsoft.InformationProtection.File;using Microsoft.Identity.Client;using System;using System.Linq;using System.Threading.Tasks;
namespace ConsoleApp5{ internal class Program { private const string clientId = "clientId"; private const string tenantId = "tenantId"; private const string appName = "SensitivityLabelReader"; private const string userEmail = "user1@demain.com"; private const string filePath = "C:\\Users\\TestdDoc.docx";
static void Main(string[] args) { try { // Initialize MIP SDK MIP.Initialize(MipComponent.File);
// Create application info var appInfo = new ApplicationInfo() { ApplicationId = clientId, ApplicationName = appName, ApplicationVersion = "1.0.0" };
// Create delegates var authDelegate = new AuthDelegateImplementation(appInfo, tenantId); var consentDelegate = new ConsentDelegateImplementation();
// Setup MIP context and profile var mipConfiguration = new MipConfiguration(appInfo, "mip_data", Microsoft.InformationProtection.LogLevel.Error, false, CacheStorageType.OnDiskEncrypted); var mipContext = MIP.CreateMipContext(mipConfiguration); var profileSettings = new FileProfileSettings(mipContext, CacheStorageType.OnDiskEncrypted, consentDelegate); var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
// Setup engine var engineSettings = new FileEngineSettings(userEmail, authDelegate, "", "en-US") { Identity = new Identity(userEmail) }; var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result;
// Display available labels Console.WriteLine("Available Sensitivity Labels:"); Console.WriteLine("=============================="); foreach (var label in fileEngine.SensitivityLabels) { Console.WriteLine($"{label.Name} : {label.Id}"); foreach (var child in label.Children) { Console.WriteLine($"\t{child.Name} : {child.Id}"); } } Console.WriteLine();
// Read label from file Console.WriteLine($"Reading sensitivity label from: {filePath}"); Console.WriteLine("===============================================");
var handler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(filePath, filePath, true)).Result; var contentLabel = handler.Label;
if (contentLabel?.Label != null) { Console.WriteLine($"Label Name: {contentLabel.Label.Name}"); Console.WriteLine($"Label ID: {contentLabel.Label.Id}"); Console.WriteLine($"Is Protected: {contentLabel.IsProtectionAppliedFromLabel}"); if (!string.IsNullOrEmpty(contentLabel.Label.Description)) Console.WriteLine($"Description: {contentLabel.Label.Description}"); if (contentLabel.Label.Parent != null) Console.WriteLine($"Parent Label: {contentLabel.Label.Parent.Name}"); } else { Console.WriteLine("No sensitivity label found on this file."); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); }
Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } }
// Authentication delegate for MIP SDK public class AuthDelegateImplementation : IAuthDelegate { private readonly ApplicationInfo _appInfo; private readonly string _tenantId;
public AuthDelegateImplementation(ApplicationInfo appInfo, string tenantId) { _appInfo = appInfo; _tenantId = tenantId; }
public string AcquireToken(Identity identity, string authority, string resource, string claims) { var authorityUri = new Uri(authority); authority = $"https://{authorityUri.Host}/{_tenantId}";
var app = PublicClientApplicationBuilder .Create(_appInfo.ApplicationId) .WithAuthority(authority) .WithDefaultRedirectUri() .Build();
var accounts = app.GetAccountsAsync().GetAwaiter().GetResult(); var scopes = new[] { resource.TrimEnd('/') + "/.default" };
var result = app.AcquireTokenInteractive(scopes) .WithAccount(accounts.FirstOrDefault()) .WithPrompt(Prompt.SelectAccount) .ExecuteAsync() .GetAwaiter() .GetResult();
return result.AccessToken; } }
// Consent delegate for MIP SDK public class ConsentDelegateImplementation : IConsentDelegate { public Consent GetUserConsent(string url) => Consent.Accept; }}
Nonetheless many consumers appreciate Mattyboyclothing for its bold identity and the way it stands out in fashion culture
ReplyDeleteKroen has faced many challenges but he never sees them as obstacles. He views each hardship as a lesson that sharpens his spirit. When others would give up he becomes even more determined. This mindset has earned him deep respect from those around him.
ReplyDeleteThe brand’s audience includes artists athletes and everyday individuals who value authenticity.
ReplyDeleteThe discounts tied to Davril Supply codes vary: some offer a flat percentage off others give tiered or conditional discounts
ReplyDeleteThe fusion of Japanese pop culture, anime influences, and traditional motifs in Murakami's clothing is unmatched. It’s not often that fashion makes you stop and think
ReplyDeleteWhether you’re dressing up or keeping it casual, Akimbo Hoodies can easily match your look. Pair them with jeans, joggers, or shorts — they adapt to your vibe.
ReplyDeleteSome of the limited drops are hard to get your hands on, but that scarcity is part of what makes Trapstar so sought after. When you see someone wearing a rare Trapstar piece, you know they’re really in the know.
ReplyDeleteThe concept of Seven Heavens appears in many religious and spiritual traditions, including Islam, Judaism, Christianity, and ancient Mesopotamian beliefs. It generally describes a layered structure of the universe, where each “heaven” or level represents a higher state of existence, purity, or closeness to the divine.
ReplyDeleteI’ve always seen Kanye’s merchandise as an extension of his albums. When Donda dropped, the merch was dark, mysterious, and minimalist — just like the music.
ReplyDeleteThe design of the God Speed Hoodie manages to be both minimal and striking at the same time. The clean front and the impactful logo placement give it a modern streetwear aesthetic
ReplyDelete