Click here to Skip to main content
15,905,612 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all

how can we check file types before uploading them ,am using c#.
i want to upload image files. only jpeg and png files are allowed.

thanks in advance
Posted
Updated 30-Oct-16 14:34pm

There are two way you can check the File types using C#.

1. Just Check that Extension of the File in File name if its Jpeg or png you can allow to upload but it quite tricky because some one has changed file extension and upload malicious file.

2. Second you have to check file extension and the file content.so any user change the file extension then it can not allow to upload the malicious file.
you can find that way into the following link.

and i wish you have to choose the second way which is most preferable view.

http://www.dotnetexpertguide.com/2011/05/validate-uploaded-image-content-in.html[^]
 
Share this answer
 
 
Share this answer
 
The bellow code works fine for validating file Extentions. you can check any type of file extentions.

C#
string fileName = FileUpload1.FileName;
string FileExtension = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
if (FileExtension == "jpeg" || FileExtension == "png")
{

    FileUpload1.SaveAs(Server.MapPath(fileName));

}



hope this will Help you.
 
Share this answer
 
v2
Comments
CHill60 27-Sep-13 8:48am    
Question answered 2 years ago. Adds nothing to the previous solutions and doesn't cater for files with a period in the name (e.g. file.2013.jpg is a valid name). Better to use the FileInfo class to get the extension - see http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900