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"Godspeed Apparel deserves way more recognition. Their drops are always on point, and you can tell they’re not just following trends—they’re setting them. It’s refreshing to see a brand with a strong identity in a saturated market."
ReplyDeleteNot gonna lie Kapital's prices are steep. But once you understand the process behind their garments from the dyeing techniques to the hand-stitched details it makes sense.
ReplyDeleteOne of Lattafa’s distinguishing features is its ability to merge deep, traditional Middle Eastern scent profiles—such as oud, amber, musk, incense, spices, and rich woods—with more contemporary and accessible notes like vanilla, fruits, florals, and gourmand touches.
ReplyDeleteJust got my Lover Boy Hat and I’m OBSESSED. The quality is amazing, and I’ve gotten compliments every time I’ve worn it. It instantly elevates even a basic fit.
ReplyDeletePink Chrome Hearts Hoodie is its craftsmanship.
ReplyDeleteTrapstar hoodies are super versatile. I wear mine with jeans, joggers, or even under a jacket during colder months. Whether I’m going to the gym
ReplyDeleteEssentials Canada is a lifestyle and fashion brand that represents a perfect blend of comfort and contemporary street culture.
ReplyDeleteNavigating Pokémon Center Online begins with intuitive menus that let users search by Pokémon name product category or new arrivals
ReplyDeleteThe thing I appreciate most about Corteiz is the mystery. No constant ads, no mainstream campaigns — just solid designs and word of mouth.
ReplyDeleteCustomers can easily find these codes through newsletters and official social media announcements.
ReplyDeleteWearing the brown Essentials hoodie feels like wrapping yourself in calm confidence. The fabric rests gently on the skin providing just the right amount of weight and texture to feel secure yet breathable.
ReplyDeleteWhen you see a Denim Tears hoodie you immediately notice how it carries both modern streetwear aesthetics and profound cultural commentary.
ReplyDeleteKażda para spodni tej marki powstaje z myślą o ciągłym rozwoju projektanci analizują nowe rodzaje tkanin
ReplyDeleteThe black SP5DER tracksuit stands as a symbol of contemporary streetwear culture.
ReplyDeleteCustomer service at Asaali Clothing deserves a shoutout! I had a sizing issue and they responded promptly and made the exchange process super easy. It's refreshing to deal with a brand that values its customers so highly. That kind of service makes me a loyal shopper.
ReplyDeleteI think Civil Regime appeals most to people who aren’t afraid to stand out or push boundaries. It's the kind of brand that speaks to creatives, artists, and individuals who want their clothing to say something about who they are. Definitely not for everyone — but that’s kind of the point.
ReplyDelete„Trapstar Polska to coÅ› wiÄ™cej niż tylko ubrania – to styl życia. NoszÄ…c ich rzeczy czujÄ™ siÄ™ częściÄ… mÅ‚odej, dynamicznej spoÅ‚ecznoÅ›ci. Fajnie, że mamy takÄ… polskÄ… markÄ™ na Å›wiatowym poziomie!”
ReplyDelete„Plecak Trapstar to Å›wietny wybór dla osób, które ceniÄ… sobie styl i funkcjonalność. Mam go od kilku miesiÄ™cy i jestem bardzo zadowolony – jest pojemny, solidnie wykonany i wyglÄ…da mega streetwearowo!”
ReplyDeleteIf you're on the fence about getting the Alchemai hoodie, just go for it. It’s easily one of the best purchases I’ve made this season. It pairs well with pretty much everything—jeans, cargos, joggers
ReplyDeleteI love how the Sean John coat combines a classic look with a modern streetwear vibe. The fit is clean, and the material feels premium. It’s definitely a piece that can elevate any outfit effortlessly.
ReplyDeleteI recently found out about the Pink Palm Puff discount codes, and they’re such a great way to save while shopping for cute and trendy items! The site already has amazing products, and getting an extra percentage off makes it even better.
ReplyDeleteThe brand frequently plays with masculine and feminine silhouettes. This has helped redefine how fashion expresses identity.
ReplyDeleteThe wind carried hints of hidden trails and forgotten stories. One sister hesitated, but the other grabbed her hand.
ReplyDeleteSP5DER Clothing is a brand that blends streetwear with urban lifestyle. Their designs are bold, featuring geometric patterns and striking color contrasts.
ReplyDeleteA "fake god" does not necessarily have to be a mythological figure or an idol made of stone or wood. It can be anything that takes the place of the true God in a person’s heart, mind, or life. In a religious context, fake gods refer to idols or false deities that people worship instead of the one true Creator.
ReplyDeleteLattafa Perfumes is a Dubai-based fragrance brand that has gained global recognition for offering high-quality, luxurious scents at budget-friendly prices. Established in 2014, Lattafa quickly became a household name in the Middle East and has since expanded its reach to international markets, including Europe, Asia, and North America.
ReplyDeleteG59 Records was founded by Ruby da Cherry and $crim (the duo $uicideboy$) as an independent platform for music outside the mainstream.
ReplyDeleteKaikai Kiki clothing is typically sold through Murakami's exhibitions, pop-up shops, and online storefronts. Pieces range from graphic tees and hoodies to more avant-garde fashion items, all infused with his unique and often surreal aesthetic. Each item functions as both wearable art and a piece of cultural commentary, addressing themes like consumerism, identity, and the blurred boundaries of East and West.
ReplyDeleteThe name “Vrunk,” a word with no dictionary definition, reflects the group’s ethos: abstract, undefined, and open to interpretation.
ReplyDeleteThe Sp5der brand was popularized by American rapper Young Thug, a style icon known for pushing boundaries both musically and fashion-wise. With his avant-garde fashion sense and fearless attitude, Young Thug helped bring Sp5der into the spotlight around 2021.
ReplyDeleteThe denim jacket has a long history. It first appeared in the early 1900s. Workers used it for durability and strength. Over time it became a fashion symbol. Celebrities wore it in films and concerts.
ReplyDelete