Dindar
Dindar

Reputation: 3235

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 ?

Upvotes: 5

Views: 30670

Answers (3)

Oded
Oded

Reputation: 499042

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.

Upvotes: 5

Mun
Mun

Reputation: 14308

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.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161783

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 asp.net?"

Upvotes: 1

Related Questions