Now we use the below code to verify the excel file encryption status.
C#.Net
using ExcelDataReader;
using ExcelDataReader.Exceptions;
using System.Text;
namespace WinFormsApp3
{
public partial class VerifyExcelFileEncrypted : Form
{
public VerifyExcelFileEncrypted()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Change file path as per you file location
string excelFilePath = "C:\\Personal\\Files\\Test.xlsx";
bool status = ExcelStatus(excelFilePath);
if (status)
{
MessageBox.Show("The Excel file is encrypted.");
}
else
{
MessageBox.Show("The Excel file is not encrypted.");
}
}
private bool ExcelStatus(string filePath)
{
try
{
using (var stream = File.OpenRead(filePath))
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (ExcelReaderFactory.CreateReader(stream)) { }
}
}
catch (InvalidPasswordException)
{
return true;
}
return false;
}
}
}
VB.Net
Imports ExcelDataReader
Imports ExcelDataReader.Exceptions
Imports System.Text
Imports System.IO
Imports System.Windows.Forms
Namespace WinFormsApp3
Public Partial Class VerifyExcelFileEncrypted
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
'Change file path as per you file location
Dim excelFilePath As String = "C:\Personal\Files\Test.xlsx"
Dim status As Boolean = ExcelStatus(excelFilePath)
If status Then
MessageBox.Show("The Excel file is encrypted.")
Else
MessageBox.Show("The Excel file is not encrypted.")
End If
End Sub
Private Function ExcelStatus(filePath As String) As Boolean
Try
Using stream = File.OpenRead(filePath)
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)
Using ExcelReaderFactory.CreateReader(stream)
End Using
End Using
Catch ex As InvalidPasswordException
Return True
End Try
Return False
End Function
End Class
End Namespace Here i am using .net core 10. So the given piece of code is very important in .net core. "Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);" . If you dont use it will throw an exception. The code line "using (ExcelReaderFactory.CreateReader(stream)) { }" us used to verify that file is encrypted or not. Now let's run the code to check the output.


