Detecting a valid Excel file


#1

I’m trying to figure out how I can determine if a file is a valid Excel file before I attempt to process it. In my web app, uses will upload a file, and I will process it, but I cannot guarantee that users won’t occasionally upload invalid files.

I have tried this.

Excel xlDoc = new Excel();
try
{
xlDoc.Open(strFileName);
}
catch (Exception)
{
Response.Write(“Invalid or corrupt Excel file”);
}

And this works to some degree. However, it “locks” the file so that it cannot be deleted. Thus, I’m forced to restart IIS to delete the file.

Any ideas?
-Steve


#2

Hi Steve,

I will check this issue. And have you tried the latest hotfix? It’s v2.3.4.


#3

Laurence,

I seem to have found a solution with the following code:

private bool FileIsValid(string _xlFile)
{
bool bIsValid = true;
Excel xlDoc = new Excel();
try { xlDoc.Open(_xlFile); }
catch { bIsValid = false; }

return bIsValid;
}

Evidentally, when I put the “return” statement inside of the try/catch block, the function was not terminating fully and something was getting locked. I have not has any problems since I modified my funcation to the above code.

-Steve