Compartir a través de


SDK de Microsoft Information Protection: Inicio rápido para volver a publicar el SDK de archivo (C#)

Información general

Para obtener información general sobre este escenario y dónde se puede usar, consulte Volver a publicar en el SDK de MIP.

Prerrequisitos

Si aún no lo ha hecho, asegúrese de completar los siguientes requisitos previos antes de continuar:

Agregar lógica para editar y volver a publicar un archivo protegido

  1. Abra la solución de Visual Studio que creó en el artículo anterior "Inicio rápido: Establecimiento y obtención de etiquetas de confidencialidad (C#)".

  2. Con el Explorador de soluciones, abra el archivo .cs en el proyecto que contiene la implementación del Main() método . El valor predeterminado es el mismo nombre que el proyecto que lo contiene, que especificó durante la creación del proyecto.

  3. Hacia la parte final del cuerpo de Main(), debajo de Console.ReadKey() y encima del bloque de apagado de la aplicación (donde lo ha dejado en el inicio rápido anterior), inserte el código siguiente.

string protectedFilePath = "<protected-file-path>" // Originally protected file's path from previous quickstart.

//Create a fileHandler for consumption for the Protected File.
var protectedFileHandler = Task.Run(async () => 
                            await fileEngine.CreateFileHandlerAsync(protectedFilePath,// inputFilePath
                                                                    protectedFilePath,// actualFilePath
                                                                    false, //isAuditDiscoveryEnabled
                                                                    null)).Result; // fileExecutionState

// Store protection handler from file
var protectionHandler = protectedFileHandler.Protection;

//Check if the user has the 'Edit' right to the file
if (protectionHandler.AccessCheck("Edit"))
{
    // Decrypt file to temp path
    var tempPath = Task.Run(async () => await protectedFileHandler.GetDecryptedTemporaryFileAsync()).Result;

    /*
        Your own application code to edit the decrypted file belongs here. 
    */

    /// Follow steps below for re-protecting the edited file. ///
    // Create a new file handler using the temporary file path.
    var republishHandler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(tempPath, tempPath, false)).Result;

    // Set protection using the ProtectionHandler from the original consumption operation.
    republishHandler.SetProtection(protectionHandler);

    // New file path to save the edited file
    string reprotectedFilePath = "<reprotected-file-path>" // New file path for saving reprotected file.

    // Write changes
    var reprotectedResult = Task.Run(async () => await republishHandler.CommitAsync(reprotectedFilePath)).Result;

    var protectedLabel = protectedFileHandler.Label;
    Console.WriteLine(string.Format("Originally protected file: {0}", protectedFilePath));
    Console.WriteLine(string.Format("File LabelID: {0} \r\nProtectionOwner: {1} \r\nIsProtected: {2}", 
                        protectedLabel.Label.Id, 
                        protectedFileHandler.Protection.Owner, 
                        protectedLabel.IsProtectionAppliedFromLabel.ToString()));
    var reprotectedLabel = republishHandler.Label;
    Console.WriteLine(string.Format("Reprotected file: {0}", reprotectedFilePath));
    Console.WriteLine(string.Format("File LabelID: {0} \r\nProtectionOwner: {1} \r\nIsProtected: {2}", 
                        reprotectedLabel.Label.Id, 
                        republishHandler.Protection.Owner, 
                        reprotectedLabel.IsProtectionAppliedFromLabel.ToString()));
    Console.WriteLine("Press a key to continue.");
    Console.ReadKey();
}
  1. Hacia el final de Main(), busque el bloque de apagado de la aplicación creado en el inicio rápido anterior y agregue las líneas de controlador siguientes para liberar recursos.

        protectedFileHandler = null;
        protectionHandler = null;
    
  2. Reemplace los valores de marcador de posición en el código fuente con los siguientes valores:

    Marcador de posición Valor
    <ruta-de-archivo-protegido> Archivo protegido del inicio rápido anterior.
    <ruta-de-archivo-reprotegido> Ruta del archivo de salida para que el archivo modificado se vuelva a publicar.

Crear y probar la aplicación

Compile y pruebe la aplicación cliente.

  1. Utiliza CTRL-SHIFT-B (Compilar Solución) para compilar tu aplicación cliente. Si no tiene errores de compilación, use F5 (Iniciar depuración) para ejecutar la aplicación.

  2. Si el proyecto se compila y se ejecuta correctamente, la aplicación puede solicitar la autenticación mediante la Biblioteca de autenticación de Microsoft (MSAL) cada vez que el SDK llama al AcquireToken() método . Si ya existen credenciales almacenadas en caché, no se le pedirá que inicie sesión y vea la lista de etiquetas, seguida de la información sobre la etiqueta aplicada y el archivo modificado.

  Personal : 73c47c6a-eb00-4a6a-8e19-efaada66dee6
  Public : 73254501-3d5b-4426-979a-657881dfcb1e
  General : da480625-e536-430a-9a9e-028d16a29c59
  Confidential : 569af77e-61ea-4deb-b7e6-79dc73653959
  Highly Confidential : 905845d6-b548-439c-9ce5-73b2e06be157
  Press a key to continue.

  Getting the label committed to file: C:\Test\Test_protected.docx
  File Label: Confidential
  IsProtected: True
  Press a key to continue.
  Originally protected file: C:\Test\Test_protected.docx
  File LabelID: 569af77e-61ea-4deb-b7e6-79dc73653959
  ProtectionOwner: User1@Contoso.OnMicrosoft.com
  IsProtected: True
  Reprotected file: C:\Test\Test_reprotected.docx
  File LabelID: 569af77e-61ea-4deb-b7e6-79dc73653959
  ProtectionOwner: User1@Contoso.OnMicrosoft.com
  IsProtected: True
  Press a key to continue.