简体   繁体   中英

how to get file extension (not from its name or from contentType)

i just want to know the posted file extension type,

     public static void UploadFile(HttpPostedFile file)
    { 
        ....

        if (file != null && file.ContentLength > 0)
        {
            string fileName = file.FileName;
            string contentType = file.ContentType;

            file.SaveAs(path);
        }

    } 

the above code gives us the contentType

but if we change the extension by hand for example if i change untitled.exe to untitled.txt contentType becomes text. but i want to know it is an exe.

is it possible? or the other way is safe? (i think no)

What you are asking about is file identification based on it's signature. This is not 100% guaranteed to work but there are utilities that can help you with this.

For instance TrID has a database of signatures that it can attempt to match the file for you and can optionally rename it as well.

File Identifier is another one.

If you are saving the file and want to keep users from getting you to save files with specific extensions on your system then you can of course check the extension using the FileInfo class. Something like this...

var invalidExtensions = new List<string>() { ".exe", ".dll" };

...

var fileInfo = new FileInfo(file.FileName);
if (invalidExtensions.Contains(fileInfo.Extension.ToLower()))
{
     // Do your cleanup on the filename because it's an extension you don't want
     //   to save...
}

It is not possible to determine original extension of a file if user has manually changed it before uploading. However some file types have headers that can be used to terminate what type of file it is. Example may be office docs, pdfs... You simply must be carefully when excepting arbitrary file from unknown sources. Extensions are for the most part a Windows feature some other os types do not use or rely on them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM