Partilhar via


File SDK - Processar arquivos .msg de e-mails (C#)

O File SDK suporta operações de rotulagem para arquivos .msg de maneira idêntica a qualquer outro tipo de arquivo, exceto que o SDK precisa do aplicativo para habilitar o sinalizador de recurso MSG. Aqui, veremos como definir essa bandeira.

Como discutido anteriormente, a instanciação de IFileEngine requer um objeto de configuração, FileEngineSettings. FileEngineSettings pode ser usado para passar parâmetros para configurações personalizadas que o aplicativo precisa definir para uma instância específica. A propriedade CustomSettings de FileEngineSettings é usada para definir o flag de enable_msg_file_type que habilita o processamento de ficheiros .msg.

Pré-requisitos

Se ainda não o fez, certifique-se de que preenche os seguintes pré-requisitos antes de continuar:

  • Primeiro, conclua Quickstart: Inicialização do aplicativo File SDK (C#), que cria uma solução inicial do Visual Studio. Este guia rápido "Como processar arquivos de mensagens de e-mail .msg (C#)" baseia-se no anterior.
  • Revise os conceitos de arquivos de e-mail do SDK MIP.
  • Opcionalmente: Revise os conceitos dos mecanismos de arquivo no MIP SDK.
  • Opcionalmente: reveja os conceitos dos manipuladores de ficheiros no MIP SDK.

Defina enable_msg_file_type e use o SDK de ficheiro para rotular ficheiro .msg

Na continuação do início rápido de inicialização do aplicativo File API, modifique o código de construção do mecanismo de arquivo para definir enable_msg_file_type flag e, em seguida, use o mecanismo de arquivo para rotular um arquivo .msg.

  1. Abra a solução Visual Studio que você criou no anterior "Guia de início rápido: inicialização do aplicativo SDK de arquivo (C#)".

  2. Usando o Gerenciador de Soluções, abra o arquivo de .cs em seu projeto que contém a implementação do Main() método. Por padrão, tem o mesmo nome do projeto que o contém, que especificou durante a criação do projeto.

  3. Remova a implementação da função Main() do quickstart anterior. Dentro do Main() corpo, insira o seguinte código. No bloco de código abaixo, o sinalizador enable_msg_file_type é definido durante a criação do mecanismo de arquivo, um arquivo .msg pode então ser processado por objetos IFileHandler criados com o mecanismo de arquivo.

    static void Main(string[] args)
    {
        // Initialize Wrapper for File SDK operations.
        MIP.Initialize(MipComponent.File);
    
        // Create ApplicationInfo, setting the clientID from Azure AD App Registration as the ApplicationId.
        ApplicationInfo appInfo = new ApplicationInfo()
        {
                ApplicationId = clientId,
                ApplicationName = appName,
                ApplicationVersion = "1.0.0"
        };
    
        // Instantiate the AuthDelegateImpl object, passing in AppInfo.
        AuthDelegateImplementation authDelegate = new AuthDelegateImplementation(appInfo);
    
        MipContext mipContext = MIP.CreateMipContext(appInfo,"mip_data",LogLevel.Trace,null,null);
    
        // Initialize and instantiate the File Profile.
        // Create the FileProfileSettings object.
        // Initialize file profile settings to create/use local state.
        var profileSettings = new FileProfileSettings(mipContext, 
                                    CacheStorageType.OnDiskEncrypted, 
                                    new ConsentDelegateImplementation());
    
        // Load the Profile async and wait for the result.
        var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
    
        // Create a FileEngineSettings object, then use that to add an engine to the profile.
        var customSettings = new List<KeyValuePair<string, string>>();
        customSettings.Add(new KeyValuePair<string, string>("enable_msg_file_type", "true"));
    
        // Create a FileEngineSettings object, then use that to add an engine to the profile.
        var engineSettings = new FileEngineSettings("user1@tenant.com", authDelegate, "", "en-US");
        engineSettings.Identity = new Identity("user1@tenant.com");
        //set custom settings for the engine
        engineSettings.CustomSettings = customSettings;
    
        //Add fileEngine to profile
        var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result;
    
        //Set file paths
        string inputFilePath = "<input-file-path>"; //.msg file to be labeled
        string actualFilePath = inputFilePath;
        string outputFilePath = "<output-file-path>"; //labeled .msg file
        string actualOutputFilePath = outputFilePath;
    
        //Create a file handler for original file
        var fileHandler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(inputFilePath, 
                                                                    actualFilePath, 
                                                                    true)).Result;
    
        // List labels available to the user and use one of them to label the MSG file.
    
        foreach (var label in fileEngine.SensitivityLabels)
        {
            Console.WriteLine(string.Format("{0} - {1}", label.Name, label.Id));
    
            if (label.Children.Count > 0)
            {
                foreach (Label child in label.Children)
                {
                    Console.WriteLine(string.Format("\t{0} - {1}", child.Name, child.Id));
                }
            }
        }
    
        string labelId = "<label-id>"; //label retrieved using file engine
    
        LabelingOptions labelingOptions = new LabelingOptions()
        {
            AssignmentMethod = options.AssignmentMethod
        };
    
        fileHandler.SetLabel(labelId, labelingOptions, new ProtectionSettings());
    
        // Commit changes, save as outputFilePath
        var result = Task.Run(async () => await fileHandler.CommitAsync(outputFilePath)).Result;
    
        // Create a new handler to read the labeled file metadata
        var handlerModified = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(outputFilePath, 
                                                                        actualOutputFilePath, 
                                                                        true)).Result;
    
        Console.WriteLine(string.Format("Original file: {0}", inputFilePath));
        Console.WriteLine(string.Format("Labeled file: {0}", outputFilePath));
        Console.WriteLine(string.Format("Label applied to file: {0}", 
            handlerModified.Label.Name));
        Console.WriteLine("Press a key to continue.");
        Console.ReadKey();
    
        // Application Shutdown
        fileHandler = null;
        handlerModified = null;
        fileEngine = null;
        fileProfile = null;
        mipContext = null;
    }
    
    

    Para obter mais detalhes sobre operações de arquivo, consulte os conceitos do manipulador de arquivos.

  4. Substitua os valores de marcadores de posição no código-fonte usando os seguintes valores:

    Marcador de posição Valor
    <caminho do arquivo de entrada> O caminho completo para um arquivo de mensagem de entrada de teste, por exemplo: c:\\Test\\message.msg.
    <caminho do arquivo de saída> O caminho completo para o arquivo de saída, que será uma cópia rotulada do arquivo de entrada, por exemplo: c:\\Test\\message_labeled.msg.
    <ID de etiqueta> O labelId recuperado através do motor de ficheiros, por exemplo: 667466bf-a01b-4b0a-8bbf-a79a3d96f720.

Crie e teste o aplicativo

Use F6 (Criar Solução) para criar o seu aplicativo cliente. Se você não tiver erros de compilação, use F5 (Iniciar depuração) para executar seu aplicativo.

    Original file: C:\Test.msg
    Labeled file: C:\Test_Labeled.msg
    Label applied to file: Confidential    
    Press a key to continue.