SDK de archivo: Procesamiento de archivos .msg de correo electrónico (C#)

El SDK de archivo admite las operaciones de etiquetado de los archivos .msg de una manera idéntica a cualquier otro tipo de archivo, excepto que el SDK necesita la aplicación para habilitar la marca de características MSG. Aquí, veremos cómo establecer esta marca.

Como se ha comentado anteriormente, la creación de instancias de IFileEngine requiere un objeto de configuración, FileEngineSettings. FileEngineSettings se puede usar para pasar parámetros para la configuración personalizada que la aplicación debe establecer para una instancia determinada. La propiedad CustomSettings de FileEngineSettings se usa para establecer la marca de enable_msg_file_type para habilitar el procesamiento de archivos .msg.

Requisitos previos

Si todavía no lo ha hecho, complete los siguientes requisitos previos antes de continuar:

Establecimiento de enable_msg_file_type y uso del SDK de archivo para etiquetar el archivo .msg

En la continuación del inicio rápido de inicialización de aplicaciones de la API de archivo, modifique el código de construcción del motor de archivos para establecer enable_msg_file_type flag y, luego, use el motor de archivos para etiquetar un mensaje .msg.

  1. Abra la solución de Visual Studio que creó en el artículo anterior "Inicio rápido: Inicialización de aplicaciones cliente del SDK de archivo (C#)".

  2. Con el Explorador de soluciones, abra el archivo .cs del proyecto que contiene la implementación del método Main(). De manera predeterminada, tiene el mismo nombre que el proyecto que lo contiene, que especificó al crear el proyecto.

  3. Elimine la implementación de la función Main() que se quitará del inicio rápido anterior. Dentro del cuerpo de Main(), inserte el código siguiente. En el bloque de código siguiente, se establece la marca enable_msg_file_type durante la creación del motor de archivos; un archivo .msg puede entonces ser procesado por los objetos IFileHandler creados usando el motor de archivo.

    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 más información sobre las operaciones de archivo, consulte Conceptos del controlador de archivos.

  4. Reemplace los valores de marcador de posición del código fuente por los valores siguientes:

    Marcador Valor
    <input-file-path> La ruta completa a un archivo de mensaje de entrada de prueba, por ejemplo: c:\\Test\\message.msg.
    <output-file-path> Ruta completa al archivo de salida, que será una copia etiquetada del archivo de entrada, por ejemplo: c:\\Test\\message_labeled.msg.
    <label-id> labelId recuperado con el motor de archivos; por ejemplo: 667466bf-a01b-4b0a-8bbf-a79a3d96f720.

Compilar y probar la aplicación

Presione F6 (Compilar solución) para compilar la aplicación cliente. Si no hay errores de compilación, presione F5 (Iniciar depuración) para ejecutar la aplicación.

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