Click here to Skip to main content
14,870,616 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to avoid malicious file upload while uploading via file upload in asp.net with c#. If i change the text file to pdf extension and upload ,I am able to validate using mime type for the PDF file(application/pdf) but not able to do so for excel file(xls/xlsx) with same code (mime type coming as application/octet-stream). I am using URL moniker dll and asp.net with c#. I am uploading only excel and PDF files and validating the file extensions initially.

What I have tried:

Code is as follows:
private extern static System.UInt32 FindMimeFromData(
      System.UInt32 pBC,
      [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
      [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
      System.UInt32 cbSize,
      [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
      System.UInt32 dwMimeFlags,
      out System.UInt32 ppwzMimeOut,
      System.UInt32 dwReserverd
  );
HttpPostedFile file = FileUpload1.PostedFile;
        byte[] document = new byte[file.ContentLength];
        file.InputStream.Read(document, 0, file.ContentLength);
        System.UInt32 mimetype;
        FindMimeFromData(0, null, document, 256, null, 0, out mimetype, 0);
        System.IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
Posted
Updated 12-Apr-21 20:55pm
v2

1 solution

Never used that dll. But these might help you. First link is example using same dll. And Second link has MIME type for Excel.
Validating MIME of a File Before Uploading in ASP.Net[^]
Common MIME types - HTTP | MDN[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900