2

If somebody renames the extension of any file (other than excel) to xls and xlsx (please dont ask me why :-( ), I need to check for its validity (if that is still a valid excel file). I am using mime type and Its not working. Am I missing anything?

const string excel2007MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const string excel2003MimeType = "application/vnd.ms-excel";

  string excelExtention = string.Empty;
            excelExtention = System.IO.Path.GetExtension(myFilePath.PostedFile.FileName).ToLower();
            string mimeType = myFilePath.PostedFile.ContentType;
            Response.Write("mime type" + mimeType + Environment.NewLine);
            if( 
                 (
                    !(excelExtention == ".xls" && mimeType == excel2003MimeType)
                    ||
                    !(excelExtention == ".xlsx" && mimeType == excel2007MimeType)
                 )
              )
            {
                Response.Write ("only excel file is permitted");
            }

I rename a jpg file to xlsx file and upload. If I print out variable mimetype, Its value is "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet". I am not sure why because the content is not an excel file. Its an image.

Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134

2 Answers2

3

To do that you'd need to attempt to open it using an Excel library, or Excel COM object itself. Microsoft doesn't support Office COM object automation in a server environment, unfortunately.

You could just read the first part of the file and check for a binary signature, but it would be a lot of work to support all possible XLS versions; and .XSLX files are simply ZIP files containing the document in several parts.

Hope that helps.

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
3

You could always use the Excel OleDB Database driver and try to open an OleDbConnection against it.

Steve Danner
  • 21,818
  • 7
  • 41
  • 51