maztt
maztt

Reputation: 12294

asp.net mvc HttpPostedFileBase getting file extension

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?

Upvotes: 71

Views: 73473

Answers (2)

Rashad Salimov
Rashad Salimov

Reputation: 1

string extension = Path.GetExtension(formFile.FileName);
string fileName = Path.GetFileNameWithoutExtension(formFile.FileName);

fileName = Path.Combine(path, Path.GetRandomFileName() + fileName + extension);

using (FileStream fs = File.Create(Path.Combine(PathConstants.RootPath, fileName)))
{
    await formFile.CopyToAsync(fs);
}
return fileName;

Upvotes: 0

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 186

Related Questions