Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
Am trying to find extension of a file being uploaded so that i can check whether its valid/not..
I have done this but the problem is content type is like this , so how can i check
C#
HttpFileCollection objHFC = HttpContext.Current.Request.Files;
HttpPostedFile objHPF = objHFC["filecontrol"];
string contentType = objHPF.ContentType.Split('/')[1].ToLower(); 

when i uploaded a wav i got the string contentType like this ["audio/x-ms-wma"]... So how can i check whether its a valid format or not. The allowed format is mp3,wav and wma
Posted
Updated 31-Mar-13 23:36pm
v3

Try this
C#
if(System.IO.Path.GetExtension(objHPF.FileName).ToLower() == "mp3" || System.IO.Path.GetExtension(objHPF.FileName).ToLower() == "wma")
{
//valid
}
 
Share this answer
 
v2
Try this code:
C#
if(objHPF !=null && objHPF.ContentLength>0)
{
    FileInfo finfo = new FileInfo(objHPF.FileName);
    string fileExtension = finfo.Extension.ToLower();
    if (fileExtension != ".mp3" && fileExtension != ".wav" && fileExtension != ".wma")
    {
        //show error message
        return;
    }
} 
 
Share this answer
 
Use Path.GetExtension[^] method to get extension of a file from it't name.

But matching file name extension with mime type and content type is an other thing.
You have a list of mime types and the matching extension here: http://webdesign.about.com/od/multimedia/a/mime-types-by-file-extension.htm[^]

But be aware, that all this are sent by the client, thus they can be altered. You can never really believe the client! So if you really need to enforce content type filtering, you need much more. In linux/unix environment there is a method called "magic bytes[^]" that can be used to guess the file type based on the content fingerprints. But I haven't found any real implementation under .net. Still, you can use a library shipped with IE, called urlmon. In this article[^] there is a sample of usage.

C#
using System.Runtime.InteropServices;

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

public static string getMimeFromFile(HttpPostedFile file)
{
    IntPtr mimeout;

    int MaxContent = (int)file.ContentLength;
    if (MaxContent > 4096) MaxContent = 4096;

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

    if (result != 0)
    {
        Marshal.FreeCoTaskMem(mimeout);
        return "";
    }

    string mime = Marshal.PtrToStringUni(mimeout);
    Marshal.FreeCoTaskMem(mimeout);

    return mime.ToLower();
}


So you can simply use this on server side to check mime type, and match with extension too. If these do not match, you have a possible evasion.
 
Share this answer
 
Comments
Zoltán Zörgő 1-Apr-13 7:45am    
Would be interesting, why the downvote? Without any comment... hmm... not really straight.
Arjun Menon U.K 2-Apr-13 0:30am    
I have heard that GetExtension Method can be tricked , so that we won't get the real extension
C#
var NameParts = Request.Files[0].FileName.Split('.');
              var extension=NameParts[NameParts.Length-1];
 
Share this answer
 
Here is best way to do..
C#
using System;
using System.IO;

class Program
{
    static void Main()
    {
	string p = @"C:\Users\Sam\Documents\Test.txt";

	string e = Path.GetExtension(p);
	if (e == ".txt")
	{
	    Console.WriteLine(e);
	}
    }
}

Output
.txt

More details see below link..
http://www.dotnetperls.com/path-getextension[^]
 
Share this answer
 

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