Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to identify the extension/type of the file using C#?

Tags:

c#

i have a workflow where user is allowed to upload any file and then that file will be read.

Now my question is if user have image file xyz.jpg and he renamed it to xyz only (extension removed) in this can we still get the type/extension of the file using/reading files data/metadata.

Thanks all

like image 752
Anil Namde Avatar asked May 13 '10 12:05

Anil Namde


2 Answers

See PInvoke.net for more detail

   [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
    static extern int FindMimeFromData(IntPtr pBC,
          [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
         [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] 
        byte[] pBuffer,
          int cbSize,
             [MarshalAs(UnmanagedType.LPWStr)]  string pwzMimeProposed,
          int dwMimeFlags,
          out IntPtr ppwzMimeOut,
          int dwReserved);

Sample usage:

  public string MimeTypeFrom(byte[] dataBytes, string mimeProposed) {
   if (dataBytes == null)
     throw new ArgumentNullException("dataBytes");
   string mimeRet = String.Empty;
   IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero, outPtr = IntPtr.Zero;
   if (mimeProposed != null && mimeProposed.Length > 0) {
     //suggestPtr = Marshal.StringToCoTaskMemUni(mimeProposed); // for your experiments ;-)
     mimeRet = mimeProposed;
   }
   int ret = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, mimeProposed, 0, out outPtr, 0);
   if (ret == 0 && outPtr != IntPtr.Zero) {
    //todo: this leaks memory outPtr must be freed
     return Marshal.PtrToStringUni(outPtr);
   }
   return mimeRet;
}

// call it this way:
Trace.Write("MimeType is " + MimeTypeFrom(Encoding.ASCII.GetBytes("%PDF-"), "text/plain"));

Another example:

/// <summary>
/// Ensures that file exists and retrieves the content type 
/// </summary>
/// <param name="file"></param>
/// <returns>Returns for instance "images/jpeg" </returns>
public static string getMimeFromFile(string file)
{
    IntPtr mimeout;
    if (!System.IO.File.Exists(file))
    throw new FileNotFoundException(file + " not found");

    int MaxContent = (int)new FileInfo(file).Length;
    if (MaxContent > 4096) MaxContent = 4096;
    FileStream fs = File.OpenRead(file);


    byte[] buf = new byte[MaxContent];        
    fs.Read(buf, 0, MaxContent);
    fs.Close();
    int result = FindMimeFromData(IntPtr.Zero, file, buf, MaxContent, null, 0, out mimeout, 0);

    if (result != 0)
    throw Marshal.GetExceptionForHR(result);
    string mime = Marshal.PtrToStringUni(mimeout);
    Marshal.FreeCoTaskMem(mimeout);
    return mime;
}
like image 54
Sky Sanders Avatar answered Sep 20 '22 11:09

Sky Sanders


You can use the unmanaged function FindMimeFromData in urlmon.dll.

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
);

See here for an example usage.

like image 25
Mark Byers Avatar answered Sep 18 '22 11:09

Mark Byers