SMK
SMK

Reputation: 2158

File upload asp.net

What is the best way to validate the file format in file-upload control in ASP.NET? Actually I want that user only upload files with specific format. Although I validate it by checking file name but I am looking for another solution to over come this.

Upvotes: 1

Views: 732

Answers (3)

Harun
Harun

Reputation: 5179

Try the following code which reads the first 256 bytes from the file and return the mime type of the file using an internal dll (urlmon.dll).Then compare the mime type of your file and the returned mime type after parsing.

     using System.Runtime.InteropServices; ...

           [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
           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
         );

         public string getMimeFromFile(string filename)
         {
          if (!File.Exists(filename))
             throw new FileNotFoundException(filename + " not found");

            byte[] buffer = new byte[256];
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
              if (fs.Length >= 256)
                  fs.Read(buffer, 0, 256);
              else
                 fs.Read(buffer, 0, (int)fs.Length);
           }
      try
      {
          System.UInt32 mimetype;
          FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
          System.IntPtr mimeTypePtr = new IntPtr(mimetype);
          string mime = Marshal.PtrToStringUni(mimeTypePtr);
          Marshal.FreeCoTaskMem(mimeTypePtr);
          return mime;
     }
     catch (Exception e)
     {
         return "unknown/unknown";
     }
    }

But check the type in different browsers, since the mimetype might be different in different browsers.

Also this will give the exact mimetype even if you changed the extension by editing the name of the file.

Hope this helps you...

Upvotes: 1

ZippyV
ZippyV

Reputation: 13068

You can use a component like Uploadify that limit's the user which type of files he can choose before uploading.

Upvotes: 0

svick
svick

Reputation: 245046

The only way to be sure is to actually parse the whole file according to the specification of the file format and check that everything fits.

If you want to do just basic check, most binary file formats have some form of header or magic number at their beginning, that you can check for.

Upvotes: 1

Related Questions