Friday, August 29, 2025

Building a Read-Only Microsoft Information Protection Sensitivity Label Reader in C#

Building a Read-Only Microsoft Information Protection Sensitivity Label Reader in C#
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:

  1. Azure AD App Registration with appropriate MIP permissions
  2. Visual Studio or .NET Framework 4.8 development environment
  3. Microsoft Information Protection SDK (via NuGet)
  4. Microsoft Authentication Library (MSAL) for authentication
  5. Files with sensitivity labels applied for testing

Azure AD App Registration Setup

First, you'll need to register an application in Azure Active Directory:

  1. Navigate to the Azure Portal → Azure Active Directory → App registrations
  2. Click "New registration"
  3. Provide a name (e.g., "Sensitivity Label Reader")
  4. Set redirect URI to http://localhost (for desktop app)
  5. 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;
    }
}


41 comments:

  1. Nonetheless many consumers appreciate Mattyboyclothing for its bold identity and the way it stands out in fashion culture

    ReplyDelete
  2. Kroen 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.

    ReplyDelete
  3. The brand’s audience includes artists athletes and everyday individuals who value authenticity.

    ReplyDelete
  4. The discounts tied to Davril Supply codes vary: some offer a flat percentage off others give tiered or conditional discounts

    ReplyDelete
  5. The 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

    ReplyDelete
  6. Whether 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.

    ReplyDelete
  7. Some 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.

    ReplyDelete
  8. The 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.

    ReplyDelete
  9. I’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.

    ReplyDelete
  10. The 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
  11. "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."

    ReplyDelete
  12. Not 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.

    ReplyDelete
  13. One 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.

    ReplyDelete
  14. Just 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.

    ReplyDelete
  15. Pink Chrome Hearts Hoodie is its craftsmanship.

    ReplyDelete
  16. Trapstar 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

    ReplyDelete
  17. Essentials Canada is a lifestyle and fashion brand that represents a perfect blend of comfort and contemporary street culture.

    ReplyDelete
  18. Navigating Pokémon Center Online begins with intuitive menus that let users search by Pokémon name product category or new arrivals

    ReplyDelete
  19. The thing I appreciate most about Corteiz is the mystery. No constant ads, no mainstream campaigns — just solid designs and word of mouth.

    ReplyDelete
  20. Customers can easily find these codes through newsletters and official social media announcements.

    ReplyDelete
  21. Wearing 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.

    ReplyDelete
  22. When you see a Denim Tears hoodie you immediately notice how it carries both modern streetwear aesthetics and profound cultural commentary.

    ReplyDelete
  23. Każda para spodni tej marki powstaje z myślą o ciągłym rozwoju projektanci analizują nowe rodzaje tkanin

    ReplyDelete
  24. The black SP5DER tracksuit stands as a symbol of contemporary streetwear culture.

    ReplyDelete
  25. Customer 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.

    ReplyDelete
  26. I 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
  27. „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
  28. „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!”

    ReplyDelete
  29. If 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

    ReplyDelete
  30. I 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.

    ReplyDelete
  31. I 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.

    ReplyDelete
  32. The brand frequently plays with masculine and feminine silhouettes. This has helped redefine how fashion expresses identity.

    ReplyDelete
  33. The wind carried hints of hidden trails and forgotten stories. One sister hesitated, but the other grabbed her hand.

    ReplyDelete
  34. SP5DER Clothing is a brand that blends streetwear with urban lifestyle. Their designs are bold, featuring geometric patterns and striking color contrasts.

    ReplyDelete
  35. A "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.

    ReplyDelete
  36. Lattafa 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.

    ReplyDelete
  37. G59 Records was founded by Ruby da Cherry and $crim (the duo $uicideboy$) as an independent platform for music outside the mainstream.

    ReplyDelete
  38. Kaikai 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.

    ReplyDelete
  39. The name “Vrunk,” a word with no dictionary definition, reflects the group’s ethos: abstract, undefined, and open to interpretation.

    ReplyDelete
  40. The 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.

    ReplyDelete
  41. The 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

Featured Post

Important links

Important Links Node Download:   https://nodejs.org/en/download   Nvm-Windows:   https://github.com/coreybutler/nvm-windows?tab=readme-ov-fi...

Popular posts