70
public string ContructOrganizationNameLogo(HttpPostedFileBase upload, string OrganizationName, int OrganizationID,string LangName)
    {
         var UploadedfileName = Path.GetFileName(upload.FileName);
        string type = upload.ContentType;
    }

I want to get the extension of the file to dynamically generate the name of the file.One way i will use to split the type. but can i use HttpPostedFileBase object to get the extension in the clean way?

tereško
  • 58,060
  • 25
  • 98
  • 150
maztt
  • 12,278
  • 21
  • 78
  • 153

1 Answers1

184

Like this:

string extension = Path.GetExtension(upload.FileName);

This will include a leading ..

Note that the you should not assume that the extension is correct.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    May be worth mentioning that determining type from byte[] is not very straightforward. ;) You'll have to assume using MagicStrings, using unmanaged code, or do investigative work like iteratively consume as various types until it doesn't fail, etc. If this is an internal app, consequences of mis-typed file uploads can be mitigated on the consuming end, and the threat of malicious use is exceedingly low, relying on the extension is probably reasonable enough compared to expense of doing the rest. Weigh your options accordingly :) – JoeBrockhaus Dec 05 '14 at 18:12
  • 1
    My file name is like "hello.zip" but this command return ".+7ip" – Sruit A.Suk Aug 03 '16 at 01:58