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, vea Repetición de la publicación en el SDK de MIP.

Requisitos previos

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

Incorporación de lógica para editar y volver a publicar un archivo protegido

  1. Abra la solución de Visual Studio que ha creado en el artículo anterior "Inicio rápido: Establecimiento u obtención de etiquetas de confidencialidad (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. 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 la parte final de Main(), busque el bloque de cierre de la aplicación creado en el inicio rápido anterior y agregue la líneas de controlador siguientes para liberar recursos.

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

    Marcador Valor
    <protected-file-path> Archivo protegido del inicio rápido anterior.
    <reprotected-file-path> Ruta del archivo de salida para que el archivo modificado se vuelva a publicar.

Compilar y probar la aplicación

Compile y pruebe la aplicación cliente.

  1. Presione CTRL-MAYÚS-B (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.

  2. Si el proyecto se compila y ejecuta correctamente, es posible que la aplicación solicite autenticación mediante la biblioteca de autenticación de Microsoft (MSAL) cada vez que el SDK llame al método AcquireToken(). Si ya existen credenciales en caché, no se le pedirá que inicie sesión y verá 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.