Remove Password/ Decrypt Excel Using C#, VB.Net in Windows Application

How to verify and remove password or decrypt excel file using c# or vb.net in windows application. .net core 10 have been used.
In today's article I will show you a simple tutorial with an example how you can remove password or decrypt the password protected excel file using c#.net and VB.net in windows application. Here we will first detect excel file is password protected or encrypted or not. If it is password protected this tutorial code will remove the password and make unprotected excel sheet. Now we will create a password protected excel file. Here is password for Excel is 123

Password Protected/ Encrypt Excel

Now we will create a new windows application and add a button control, in click on button click we will verify and remove the password from the excel file. First, we will install the ExcelDataReader NuGet package.

ExcelDataReader NuGet package

C#.Net

using ExcelDataReader;
using ExcelDataReader.Exceptions;
using System.Runtime.InteropServices;
using System.Text;

namespace WinFormsApp3
{
    public partial class VerifyExcelFileEncrypted : Form
    {
        public VerifyExcelFileEncrypted()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string excelFilePath = "C:\\Personal\\Files\\Test.xlsx";
            bool status = ExcelStatus(excelFilePath);
            if (status)
            {
                try
                {
                    // Provide the current password for the workbook
                    string currentPassword = "123";

                    // Remove password using Excel COM automation (requires Excel installed)
                    RemovePasswordWithExcelInterop(excelFilePath, currentPassword);
                    MessageBox.Show("Password removed (file overwritten).");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to remove password: " + ex.Message);
                }
            }
            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;
        }

        /// <summary>
        /// Remove password.
        /// </summary>
        private void RemovePasswordWithExcelInterop(string filePath, string password)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException("Excel file not found.", filePath);

            Type excelType = Type.GetTypeFromProgID("Excel.Application");
            if (excelType == null)
                throw new InvalidOperationException("Microsoft Excel is not installed on this machine.");

            object excel = null;
            object workbook = null;
            try
            {
                excel = Activator.CreateInstance(excelType);
                dynamic app = excel;
                app.DisplayAlerts = false;
                app.Visible = false;

                // Open the workbook providing the password
                workbook = app.Workbooks.Open(filePath, ReadOnly: false, Password: password);

                // Use dynamic to call SaveAs on the workbook
                dynamic wb = workbook;
                wb.SaveAs(Filename: filePath, Password: "", WriteResPassword: "", ReadOnlyRecommended: false, CreateBackup: false);
                wb.Close(SaveChanges: false);
            }
            finally
            {
                // Cleanup COM objects
                try
                {
                    if (workbook != null)
                        Marshal.ReleaseComObject(workbook);
                }
                catch { /* ignore */ }

                try
                {
                    if (excel != null)
                    {
                        try
                        {
                            ((dynamic)excel).Quit();
                        }
                        catch { /* ignore */ }
                        Marshal.ReleaseComObject(excel);
                    }
                }
                catch { /* ignore */ }

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }
} 

VB.Net

 Imports ExcelDataReader
Imports ExcelDataReader.Exceptions
Imports System.Runtime.InteropServices
Imports System.Text

Namespace WinFormsApp3
    Public Partial Class VerifyExcelFileEncrypted
        Inherits Form
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub button1_Click(sender As Object, e As EventArgs)
            Dim excelFilePath = "C:\Personal\Files\Test.xlsx"
            Dim status = ExcelStatus(excelFilePath)
            If status Then
                Try
                    ' Provide the current password for the workbook
                    Dim currentPassword = "123"

                    ' Remove password using Excel COM automation (requires Excel installed)
                    RemovePasswordWithExcelInterop(excelFilePath, currentPassword)
                    MessageBox.Show("Password removed (file overwritten).")
                Catch ex As Exception
                    MessageBox.Show("Failed to remove password: " & ex.Message.ToString())
                End Try
            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 __unusedInvalidPasswordException1__ As InvalidPasswordException
                Return True
            End Try
            Return False
        End Function

        ''' <summary>
        ''' Remove password.
        ''' </summary>
        Private Sub RemovePasswordWithExcelInterop(filePath As String, password As String)
            If Not File.Exists(filePath) Then Throw New FileNotFoundException("Excel file not found.", filePath)

            Dim excelType = Type.GetTypeFromProgID("Excel.Application")
            If excelType Is Nothing Then Throw New InvalidOperationException("Microsoft Excel is not installed on this machine.")

            Dim excel As Object = Nothing
            Dim workbook As Object = Nothing
            Try
                excel = Activator.CreateInstance(excelType)
                Dim app As dynamic = excel
                app.DisplayAlerts = False
                app.Visible = False

                ' Open the workbook providing the password
                workbook = app.Workbooks.Open(filePath, [ReadOnly]:=False, Password:=password)

                ' Use dynamic to call SaveAs on the workbook
                Dim wb As dynamic = workbook
                wb.SaveAs(Filename:=filePath, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False)
                wb.Close(SaveChanges:=False)
            Finally
                ' Cleanup COM objects
                Try
                    If workbook IsNot Nothing Then Marshal.ReleaseComObject(workbook)
                Catch
                End Try

                Try
                    If excel IsNot Nothing Then
                        Try
                            CType(excel, dynamic).Quit()
                        Catch
                        End Try
                        Marshal.ReleaseComObject(excel)
                    End If

                Catch
                End Try

                GC.Collect()
                GC.WaitForPendingFinalizers()
            End Try
        End Sub
    End Class
End Namespace 

In above code first I have stored the path of excel file in a variable. Afte that i have created a method to verify that the file is password protected or not. If it is password protected on that a new variable i have defined where I passed the password of the excel file.

Now I have created a separate method named as RemovePasswordWithExcelInterop(excelFilePath, currentPassword);. In this method I have passed excel file and current password of the excel file. Here I have used Excel COM to open the excel with provided password and saved back the excel without password. This code will require Excel to be installed on the machine. Now we have done, lets run the code and check output. First, we will remove password and after that we will again check the file.

Remove Excel file password

Now let's rerun the application and check again for decrypted file. Here we will get message that file is not encrypted. 

Decrypted Excel file

Post a Comment