please read the following details because my scenarios are different.
My project need the small functionality of reading data from excel file and writing data to excel file through c#.
I am providing the two options for user 1. Create Excel file 2.Open Existing excel file
if user select option 1 then it will ask to user that does he want to protect file by setting password or not
1.set password
2.No I don't want to set password
in this way my file will be saved.(please consider file path is already given)
now if user want to open the file then i need to check whether the file is password protected or not.
if file is password protected I want to ask for pass, otherwise not
problem is that--I want to check the file is password protected or not. I tried that by using 'HasPassword' property of WorkBook
if(WorkBookObj.HasPassword)
{
//ask for pass and call method with pass
ExcelFileObj.OpenExcelFile(UserEnteredPath,userEnteredPass);
}
else
{
//no need to ask for pass
ExcelFileObj.OpenExcelFile(UserEnteredPath);
}
I did code like above
OpenExcel file method is like this
public void OpenExcelFile(FilePath,string password)
{
try
{
XlWorkbook = XlApp.Workbooks.Open(FilePath, Password: password);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
like wise i also have the another overloaded method OpenExcelFile(filePath)
I came to know that HasPassword only work when File is open. But I want that before opening the file because I want to call different method depending upon the value of HasPassword property. Please suggest some solution for this.
what i tried---i was trying to solve that by catching the exception which is thrown by this Method
XlWorkbook = XlApp.Workbooks.Open(FilePath, Password: password);
firstly I called the overloaded Open(Password) method if the file is password protected it will through exception and i can do my stuff (i.e asking to user for pass) but here problem is that
XlWorkbook = XlApp.Workbooks.Open(FilePath, Password: password);
this method can though different exception like file not found, password is not correct etc these all are of type "System.Runtime.InteropServices.COMException" so I can not use multiple catch statement to catch different type of exception like "System.Io.FileNotFoundException",....etc if I try to do that it will say exception class must be Inherited from System.Exception. so please suggest any solution for this.
or is there any unique thing (like ErrorCode..etc)which will differentiate the two exception like file not found, password is not correct etc
Thanks in advance....