首页 > 解决方案 > Check Excel has password and prevent Prompt C#

问题描述

I have looked on the internet and on this site as to how to check if file has a password. The problem is how to prevent Excel prompting you for a correct password. I see there's HasPassword but it seems to me that property is only useable when the sheet has been opened.

try {
oWrkBk = oApp.Workbooks.Open(sFile, Password: "");
}
catch { /* has password */

But the problem is, the Excel open a prompt window which I don't want. If I can't open it, I'll skip it and close the Excel window down.

标签: c#excel

解决方案


除非OleDb不可能,否则您将能够使用它来确定文件是否具有基于是否引发异常的密码。

要显示的示例代码:

//using System.Data.OleDb;
private static void OpenMyExcel()
{
    string filePath = "C:\\users\\me\\Desktop\\Book1.xlsx";
    OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\"");

    try
    {
        connection.Open();
        //Do stuff
    }
    catch(Exception e)
    {
        //has a password
    }
}

可以改为简单的检查方法(对于业余代码抱歉):

//using System.Data.OleDb;
private static bool HaveAPass(string filePath)
{
    OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\"");

    try
    {
        connection.Open();
        connection.Close(); //if it reaches this point, there is no password
        return false;
    }
    catch(Exception e)
    {
        //has a password
        return true;
    }
}

推荐阅读