c#验证excel文件是否损坏,如果损坏,则弹出一个消息框

c#验证excel文件是否损坏,如果损坏,则弹出一个消息框,c#,excel,vba,C#,Excel,Vba,我是c#的新手,我正在做一个窗口窗体程序来检查excel文件是否存在。如果存在,则需要验证excel文件是否损坏,但我不知道如何编写代码。搜索excel文件的部分我已经做了。 # int点=0; 如果(文件.Exists(路径1[0])) { MessageBox.Show(“销售”+年+“-”+月+“-”+日+“传输错误”); 点=1; } 其他的 { for(int x=1;x

我是c#的新手,我正在做一个窗口窗体程序来检查excel文件是否存在。如果存在,则需要验证excel文件是否损坏,但我不知道如何编写代码。搜索excel文件的部分我已经做了。 #

int点=0;
如果(文件.Exists(路径1[0]))
{
MessageBox.Show(“销售”+年+“-”+月+“-”+日+“传输错误”);
点=1;
}
其他的
{
for(int x=1;x
看起来您需要检查多个路径是否存在和文件格式?如果是这样,请以更好的方式构造代码。但是,下面的函数将为您提供预期的结果。这使用EPPlus库,通过nuget安装

enum ExcelFileTestResult
{
    FileNotFound,
    ValidFormat, //File found, valid excel
    InvalidFormat //File found but not valid excel
}

public static ExcelFileTestResult CheckExcelFile(string path)
{
    ExcelFileTestResult result = ExcelFileTestResult.FileNotFound;
    if (File.Exists(path))
    {
        FileInfo fi = new FileInfo(path);
        try
        {
            // Trying to read file using EPPlus
            // if the file is not valid format, it will throw error
            using (ExcelPackage p = new ExcelPackage(fi))
            {
                result = ExcelFileTestResult.ValidFormat;
            }
        }
        catch (InvalidDataException ex)
        {
            result = ExcelFileTestResult.InvalidFormat;
        }
    }
    return result;
}
注意:EPPlus仅适用于xlsx,不适用于xls。

看起来您需要检查多个路径是否存在和文件格式?如果是这样,请以更好的方式构造代码。但是,下面的函数将为您提供预期的结果。这使用EPPlus库,通过nuget安装

enum ExcelFileTestResult
{
    FileNotFound,
    ValidFormat, //File found, valid excel
    InvalidFormat //File found but not valid excel
}

public static ExcelFileTestResult CheckExcelFile(string path)
{
    ExcelFileTestResult result = ExcelFileTestResult.FileNotFound;
    if (File.Exists(path))
    {
        FileInfo fi = new FileInfo(path);
        try
        {
            // Trying to read file using EPPlus
            // if the file is not valid format, it will throw error
            using (ExcelPackage p = new ExcelPackage(fi))
            {
                result = ExcelFileTestResult.ValidFormat;
            }
        }
        catch (InvalidDataException ex)
        {
            result = ExcelFileTestResult.InvalidFormat;
        }
    }
    return result;
}
注意:EPPlus仅适用于xlsx,不适用于xls。

请检查并确认。编辑您的帖子以包含实际问题。“不知道如何编写代码”不是一个有效的问题。什么样的文件-.xls、xlsx或两者都有?我不确定,但你可以尝试通过第三方LIB打开它。如果文件损坏,库将无法打开它并为您抛出异常。很抱歉,因为我本周从这里开始学习c#,这是我第一次在这里提出问题//,只有.xlsx文件//请查看并重试。编辑您的帖子以包含实际问题。“不知道如何编写代码”不是一个有效的问题。什么样的文件-.xls、xlsx或两者都有?我不确定,但你可以尝试通过第三方LIB打开它。如果文件损坏,库将无法打开它并为您抛出异常。很抱歉,因为我本周从这里开始学习c#,这是我第一次在这里问问题//,仅.xlsx文件//