Getting extension of the file in FileUpload Control

At the moment i get file extension of the file like :

string fileExt = System.IO.Path.GetExtension(filUpload.FileName);

But if the user change the file extension of the file ( for example user could rename “test.txt” to “test.jpg” ), I can’t get the real extension . What’s the solution ?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You seem to be asking if you can identify file-type from its content.

Most solutions will indeed attempt the file extension, but there are too many different possible file types to be reliably identifiable.

Most approaches use the first several bytes of the file to determine what they are.

Here is one list, here another.

If you are only worried about text vs binary, see this SO question and answers.

See this SO answer for checking if a file is a JPG – this approach can be extended to use other file headers as in the first two links in this answer.

Method 2

Whatever the user renames the file extension to, that is the real file extension.

You should never depend on the file extension to tell you what’s in the file, since it can be renamed.

See “how can we check file types before uploading them in

Method 3

There’s no way to get the ‘real’ file extension – the file extension that you get from the filename is the real one. If file content is your concern, you can retrieve the content type using the .ContentType property and verify that it is a content type that you are expecting – eg. image/jpg.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x