Search code examples
excelazureblobeppluspassword-protection

Azure Blob Storage: Remove password from excel workbook


I have a password-protected excel workbook saved in Azure Blob storage and I would like to remove the password and upload the file back to the blob. I wrote code to password protect an excel file in the blob but I am new to C# and opening the password protected file as a stream generates an error.

Has anyone had success removing the password from an excel file saved in Azure Blob storage?

//Open Excel on blob
            BlobServiceClient blobServiceClient = new BlobServiceClient(appsetting);
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            //Password protect file
            using (var stream = await blobClient.OpenReadAsync(new BlobOpenReadOptions(true)))
            using (ExcelPackage package = new ExcelPackage(stream))
            {
                //Save password protected file
                package.Save(password);
                MemoryStream ms = new MemoryStream(package.GetAsByteArray());
                ms.Position = 0;

                //Delete the unprotected excel file
                blobClient.DeleteIfExists();

                //Upload password protected excel file
                BlobClient outputBlob = containerClient.GetBlobClient(fileName);
                outputBlob.Upload(ms);
            }

Solution

  • Solved by saving to a temp folder on Azure and then opening the file.

    //Create temp path
    string tempPath = Path.GetTempPath();
    tempFullPath = tempPath + fileName;
    
     //Download blob
     blobClient.DownloadTo(tempFullPath);