4

I know the file's name, that is saved on server, I want to get the contentType of that file that is saved on server, what I want is something like this:

string loc = Server.MapPath("~/Content/Images/document.*");

But the above code is not working and the error says :

Illegal character is specified i.e.(*)

My question is, how to get the extension and the content type of the file name that I know and is saved on server?

3
  • 4
    Once stored on the disk, there's no longer a notion of ContentType. So basically you could associate this information with the file by the time it gets uploaded and persist it in your datastore. Then just look at the datastore the corresponding ContentType given a filename. On the other hand if all you need is the file extension, then this is quite easy using the Path.GetExtension method. Commented Mar 25, 2017 at 17:03
  • @darin said absolutely marvelous answer. A shortest and fastest solution of what u asked for. Commented Mar 25, 2017 at 17:05
  • @DarinDimitrov That's the answer, can you let me mark it as the answer? Commented Mar 27, 2017 at 8:43

1 Answer 1

9

Are you looking for the file extension or the content-type (mime-type) of the file?

If you are looking for the file extension you can use Path.GetExtension:

var fileExt = Path.GetExtension(Server.MapPath("a.txt"));
// returns ".txt"

If you are looking for file mime type make use of MimeMapping.GetMimeMapping

var mimeType  = MimeMapping.GetMimeMapping("a.txt");
// returns "plain/text"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.