Checking if an Excel file is an Excel file using EPPlus

I am using EPPlus in C # to read an Excel file (.xlsx). Initialization is performed as follows:

var package = new ExcelPackage(new FileInfo(filename));

This works fine, but is there a way to check if the specified filenameor packagevalid .xlsx file is really? Otherwise, there will be exceptions when working on an object other than Excel, for example. if the user accidentally opened a .zip file or something else.

+5
source share
1 answer

You can check your file extension:

string file = @"C:\Users\Robert\Documents\Test.txt";

string extenstion = Path.GetExtension(file);

Update

I did not find any return values ​​for the situation when some file cannot be opened in the EPPlus documentation, but you can use this to catch it:

FileInfo fileInfo = new FileInfo(pathToYourFile);

ExcelPackage package = null;
try
{
    package = new ExcelPackage(fileInfo);
}
catch(Exception exception)
{
   ...
}

catch - , .

+3

All Articles