You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助MIP SDK移除Excel保护并导入VB.NET WinForms应用?

在VB.NET WinForms中自动移除Excel文件的MIP保护/修改敏感度标签

前置准备

  • 安装MIP SDK NuGet包:在VB.NET项目中安装Microsoft.InformationProtection.File和Microsoft.InformationProtection.Protection两个NuGet包
  • 注册Azure AD应用:创建一个Azure AD应用,获取客户端ID、租户ID,配置客户端密码/证书,并授予Files.ReadWrite.All、InformationProtectionPolicy.Read.All等必要权限,确保权限已被租户管理员批准

具体实现步骤

1. 初始化MIP SDK

先完成MIP的配置与客户端初始化,实现身份验证逻辑:

Imports Microsoft.InformationProtection
Imports Microsoft.InformationProtection.File
Imports Microsoft.InformationProtection.Protection
Imports Microsoft.Identity.Client

' 全局存储MIP实例
Private mipConfig As IConfiguration
Private mipFileClient As IFileClient

Public Async Function InitializeMipAsync(clientId As String, tenantId As String, clientSecret As String) As Task
    ' 构建MIP配置
    mipConfig = New ConfigurationBuilder() _
        .SetAppName("你的WinForms应用名") _
        .SetAppVersion("1.0.0") _
        .SetAuthenticationDelegate(New MipAuthDelegate(clientId, tenantId, clientSecret)) _
        .Build()

    ' 初始化SDK
    Await MIP.InitializeAsync(mipConfig)

    ' 创建文件操作客户端
    Dim profileSettings = New FileProfileSettings(mipConfig, IdentityType.AzureAd)
    Dim profile = Await FileProfile.CreateAsync(profileSettings)
    mipFileClient = Await profile.AddFileClientAsync()
End Function

' 自定义身份验证委托,处理令牌获取
Private Class MipAuthDelegate
    Implements IAuthenticationDelegate
    Private _clientId As String
    Private _tenantId As String
    Private _clientSecret As String

    Public Sub New(clientId As String, tenantId As String, clientSecret As String)
        _clientId = clientId
        _tenantId = tenantId
        _clientSecret = clientSecret
    End Sub

    Public Async Function AcquireTokenAsync(authParams As AuthenticationParameters) As Task(Of String) Implements IAuthenticationDelegate.AcquireTokenAsync
        ' 使用客户端凭据流获取访问令牌
        Dim authority = $"https://login.microsoftonline.com/{_tenantId}"
        Dim app = ConfidentialClientApplicationBuilder.Create(_clientId) _
            .WithClientSecret(_clientSecret) _
            .WithAuthority(New Uri(authority)) _
            .Build()
        Dim result = Await app.AcquireTokenForClient({authParams.Scope}).ExecuteAsync()
        Return result.AccessToken
    End Function
End Class

2. 处理受保护的Excel文件

实现移除保护或替换为无限制访问标签的逻辑:

Public Async Function ProcessProtectedExcel(inputPath As String, outputPath As String) As Task
    ' 加载受保护文件
    Dim fileHandler = Await mipFileClient.CreateFileHandlerAsync(
        inputPath,
        FileHandlerSettings.FromProtectionSettings(New ProtectionSettings()))

    ' 方案1:直接生成无保护的文件副本
    Dim unprotectedBytes = Await fileHandler.GetContentAsync()
    Await File.WriteAllBytesAsync(outputPath, unprotectedBytes)

    ' 方案2:替换为"无限制访问"敏感度标签(需匹配你的租户标签名称)
    ' Dim policyClient = Await mipFileClient.GetPolicyClientAsync()
    ' Dim policy = Await policyClient.GetPolicyAsync()
    ' Dim unrestrictedLabel = policy.Labels.FirstOrDefault(Function(l) l.Name.Equals("无限制访问", StringComparison.OrdinalIgnoreCase))
    ' If unrestrictedLabel IsNot Nothing Then
    '     Await fileHandler.SetLabelAsync(unrestrictedLabel.Id, LabelingOptions.Default)
    '     Dim updatedBytes = Await fileHandler.GetContentAsync()
    '     Await File.WriteAllBytesAsync(outputPath, updatedBytes)
    ' End If

    ' 释放资源
    fileHandler.Dispose()
End Function

3. 在WinForms界面中调用

在按钮点击等事件中触发文件处理:

Private Async Sub btnProcessFile_Click(sender As Object, e As EventArgs) Handles btnProcessFile.Click
    Try
        ' 替换为你的Azure AD应用信息
        Dim clientId = "你的客户端ID"
        Dim tenantId = "你的租户ID"
        Dim clientSecret = "你的客户端密码"

        ' 初始化MIP
        Await InitializeMipAsync(clientId, tenantId, clientSecret)

        ' 通过文件选择框获取输入输出路径
        Using openDialog As New OpenFileDialog()
            openDialog.Filter = "Excel文件|*.xlsx;*.xls"
            If openDialog.ShowDialog() = DialogResult.OK Then
                Using saveDialog As New SaveFileDialog()
                    saveDialog.Filter = "Excel文件|*.xlsx"
                    If saveDialog.ShowDialog() = DialogResult.OK Then
                        Await ProcessProtectedExcel(openDialog.FileName, saveDialog.FileName)
                        MessageBox.Show("文件处理完成")
                    End If
                End Using
            End If
        End Using
    Catch ex As Exception
        MessageBox.Show($"处理失败:{ex.Message}")
    End Try
End Sub

注意事项

  • 若文件是密码保护而非MIP敏感度标签保护,此方法不适用,需单独处理密码移除逻辑
  • 处理大文件时,建议改用流操作读取/写入内容,避免内存占用过高
  • 确保Azure AD应用的权限已完成管理员授权,否则会出现令牌获取失败的问题

内容的提问来源于stack exchange,提问作者Dev Inspirer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:05:32