Back to Devexpress

How to: Open and Save Password-Encrypted Files

officefileapi-401442-spreadsheet-document-api-examples-protection-how-to-open-and-save-password-encrypted-files.md

latest7.8 KB
Original Source

How to: Open and Save Password-Encrypted Files

  • Nov 22, 2019
  • 4 minutes to read

The Spreadsheet Document API can open and save password encrypted files in binary (.xls, .xlsb) and OpenXml (.xlsx) formats.

Open an Encrypted File

Specify the WorkbookImportOptions.Password property to decrypt a loaded file. The table below lists a chain of events raised if the Password property is not specified or returns an invalid password.

EventDescription
Workbook.EncryptedFilePasswordRequestRaised if the Password property is not specified or returns an invalid password. Use the EncryptedFilePasswordRequestEventArgs.Password property to specify a new password.
Workbook.EncryptedFilePasswordCheckFailedRaised if the EncryptedFilePasswordRequestEventArgs.Password is set to an empty or invalid password. Handle this event to obtain the error that led to this event (EncryptedFilePasswordCheckFailedEventArgs.Error) and determine whether to prompt a user for a password (EncryptedFilePasswordCheckFailedEventArgs.TryAgain).
Workbook.InvalidFormatExceptionOccurs when the EncryptedFilePasswordCheckFailedEventArgs.TryAgain property is set to false.

The following code snippet handles the Workbook.EncryptedFilePasswordRequest and Workbook.EncryptedFilePasswordCheckFailed events to prompt users to enter a password. If the user cancels the operation, the Spreadsheet Document API shows an exception message and cancels the file loading operation.

View Example: Load and Save Password-Encrypted Files

csharp
static bool IsValid { get; set; }

static void Main(string[] args) {
    Workbook workbook = new Workbook();

    workbook.EncryptedFilePasswordRequest += Workbook_EncryptedFilePasswordRequest;
    workbook.EncryptedFilePasswordCheckFailed += Workbook_EncryptedFilePasswordCheckFailed;
    workbook.InvalidFormatException += Workbook_InvalidFormatException;

    workbook.LoadDocument("Documents\\encrypted.xlsx");
}

private static void Workbook_EncryptedFilePasswordRequest(object sender, EncryptedFilePasswordRequestEventArgs e) {
    //Prompt the user to enter the password
    Console.WriteLine("Enter password:");
    e.Password = Console.ReadLine();
    e.Handled = true;
    IsValid = true;
}

private static void Workbook_EncryptedFilePasswordCheckFailed(object sender, EncryptedFilePasswordCheckFailedEventArgs e) {
    //Analyze the password error:
    switch (e.Error) {

        //If the password is empty, raise the request again
        case SpreadsheetDecryptionError.PasswordRequired:
            Console.WriteLine("You did not enter the password!");
            e.TryAgain = true;
            e.Handled = true;
            break;
        //If the password is invalid, ask user whether to continue the operation:
        case SpreadsheetDecryptionError.WrongPassword:
            Console.WriteLine("The password is incorrect. Try Again? (y/n)");
            string answer = Console.ReadLine()?.ToLower();
            if (answer == "y") {
                e.TryAgain = true;
                e.Handled = true;
            }
            //If user cancels the operation, show an exception message:
            else {
                IsValid = false;
            }
            break;
    }
    Program.IsValid = false;
}

    private static void Workbook_InvalidFormatException(object sender, SpreadsheetInvalidFormatExceptionEventArgs e) {
    Console.WriteLine(e.Exception.Message.ToString() + " Press any key to close...");
    Console.ReadKey(true);
}
vb
Private Shared Property IsValid As Boolean

Shared Sub Main(ByVal args() As String)
    Dim workbook As New Workbook()

    AddHandler workbook.EncryptedFilePasswordRequest, AddressOf Workbook_EncryptedFilePasswordRequest
    AddHandler workbook.EncryptedFilePasswordCheckFailed, AddressOf Workbook_EncryptedFilePasswordCheckFailed
    AddHandler workbook.InvalidFormatException, AddressOf Workbook_InvalidFormatException

    workbook.LoadDocument("Documents\encrypted.xlsx")
End Sub

Private Shared Sub Workbook_EncryptedFilePasswordRequest(ByVal sender As Object, ByVal e As EncryptedFilePasswordRequestEventArgs)
    'Prompt the user to enter the password
    Console.WriteLine("Enter password:")
    e.Password = Console.ReadLine()
    e.Handled = True
    IsValid = True
End Sub

Private Shared Sub Workbook_EncryptedFilePasswordCheckFailed(ByVal sender As Object, ByVal e As EncryptedFilePasswordCheckFailedEventArgs)
    'Analyze the password error:
    Select Case e.Error

        'If the password is empty, raise the request again
        Case SpreadsheetDecryptionError.PasswordRequired
            Console.WriteLine("You did not enter the password!")
            e.TryAgain = True
            e.Handled = True

        'If the password is invalid, ask user whether to continue the operation:
        Case SpreadsheetDecryptionError.WrongPassword
            Console.WriteLine("The password is incorrect. Try Again? (y/n)")
            Dim answer As String = Console.ReadLine()?.ToLower()
            If answer = "y" Then
                e.TryAgain = True
                e.Handled = True

            'If user cancels the operation, show an exception message:
            Else
                IsValid = False
            End If
    End Select

    Program.IsValid = False
End Sub

Private Shared Sub Workbook_InvalidFormatException(ByVal sender As Object, ByVal e As SpreadsheetInvalidFormatExceptionEventArgs)
    Console.WriteLine(e.Exception.Message.ToString() & " Press any key to close...")
    Console.ReadKey(True)
End Sub

The Workbook.EncryptedFileIntegrityCheckFailed event occurs if the document did not pass the code verification.

Encrypt a Workbook with a Password

Call the Workbook.SaveDocument method overloads to password-protect the document on save. Use the EncryptionOptions object properties to specify password and protection type. Use the DocumentSettings.Encryption property to access the EncryptionOptions object.

csharp
EncryptionSettings encryptionOptions = new EncryptionSettings();
encryptionOptions.Type = EncryptionType.Strong;
encryptionOptions.Password = "12345";

workbook.SaveDocument(fileName, documentFormat, encryptionOptions);
vb
Dim encryptionOptions As New EncryptionSettings()
encryptionOptions.Type = EncryptionType.Strong
encryptionOptions.Password = "12345"

workbook.SaveDocument(fileName, documentFormat, encryptionOptions)