windowsforms-17597-controls-and-libraries-spreadsheet-examples-protection-how-to-open-and-save-a-password-encrypted-file.md
When SpreadsheetControl loads a password encrypted file and the WorkbookImportOptions.Password property is not set or contains an incorrect password, the end-user is prompted for a password with the following dialog:
You can specify a password in code and not show the dialog, as illustrated in the code below.
The code snippet handles the SpreadsheetControl.EncryptedFilePasswordRequest event to specify a password for loading a password encrypted file.
private void SpreadsheetControl1_EncryptedFilePasswordRequest(object sender, EncryptedFilePasswordRequestEventArgs e) {
if (e.DocumentName == "encrypted_test.xlsx") e.Password = "test";
if (e.DocumentName == "corrupted.xlsx") e.Password = "000";
e.Handled = true;
}
Private Sub SpreadsheetControl1_EncryptedFilePasswordRequest(ByVal sender As Object, ByVal e As EncryptedFilePasswordRequestEventArgs)
If e.DocumentName = "encrypted_test.xlsx" Then
e.Password = "test"
End If
If e.DocumentName = "corrupted.xlsx" Then
e.Password = "000"
End If
e.Handled = True
End Sub
SpreadsheetControl can handle a situation when the encrypted file is corrupted.
This code snippet handles the SpreadsheetControl.EncryptedFileIntegrityCheckFailed event to perform certain actions when loading a corrupted password encrypted file.
private void SpreadsheetControl1_EncryptedFileIntegrityCheckFailed(object sender, EncryptedFileIntegrityCheckFailedEventArgs e) {
e.Cancel = true;
e.Handled = true;
MessageBox.Show("File is corrupted. Cannot load.","Warning");
}
Private Sub SpreadsheetControl1_EncryptedFileIntegrityCheckFailed(ByVal sender As Object, ByVal e As EncryptedFileIntegrityCheckFailedEventArgs)
e.Cancel = True
e.Handled = True
MessageBox.Show("File is corrupted. Cannot load.","Warning")
End Sub
To save a password encrypted file, use the Encrypt Document dialog or specify the EncryptionOptions settings in code.
This code snippet obtains the DocumentSettings.Encryption settings selected in the editors and prompts for saving a password encrypted file.
IWorkbook workbook = spreadsheetControl1.Document;
workbook.DocumentSettings.Encryption.Type = (EncryptionType)Enum.Parse(typeof(EncryptionType), barEncryptionTypeComboBox.EditValue.ToString());
workbook.DocumentSettings.Encryption.Password = barPasswordEdit.EditValue.ToString();
spreadsheetControl1.SaveDocumentAs();
Dim workbook As IWorkbook = spreadsheetControl1.Document
workbook.DocumentSettings.Encryption.Type = DirectCast(System.Enum.Parse(GetType(EncryptionType), barEncryptionTypeComboBox.EditValue.ToString()), EncryptionType)
workbook.DocumentSettings.Encryption.Password = barPasswordEdit.EditValue.ToString()
spreadsheetControl1.SaveDocumentAs()