简体   繁体   中英

Checking if file actually is an Excel file using EPPlus

I'm using EPPlus in C# to read an Excel (.xlsx) file. The initialization is done like this:

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

This works fine but is there any way to check if the specified filename or package is actually a valid .xlsx file? Otherwise there will be exceptions when operating on a non-Excel object, eg if the user accidentially opens a .zip file or else.

You can check the extension of your file:

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

string extenstion = Path.GetExtension(file);

Update

I havent found some kind of return values for the situation that some file cannot be open in the EPPlus documentation, but you can use this to catch the excetptions:

FileInfo fileInfo = new FileInfo(pathToYourFile);

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

If you are not in catch - thats mean it was opened correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM