asp.net mvc HttpPostedFileBase getting file extension
Asked Answered
Z

2

71
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?

Zulazulch answered 28/5, 2010 at 13:46 Comment(1)
Check This: codingfusion.com/Post/…Mister
T
186

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.

Taskwork answered 28/5, 2010 at 13:49 Comment(2)
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 :)However
My file name is like "hello.zip" but this command return ".+7ip"Tympan
Z
0
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;
Zaporozhye answered 17/1 at 8:39 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Corposant

© 2022 - 2024 — McMap. All rights reserved.