Waqar Malik Waqar Malik - 2 months ago 8
ASP.NET (C#) Question

Pass in file variable user uploads in return message?

What my code does it reads the file extension and if it doesn't match the

Web.config
settings then it throws message invalid file extension.

However now I want the same message thrown but with the file user uploaded such as i.e. if they upload
TEST1.DOCX
error message should appear as:

Invalid file extension for uploaded file
TEST1.DOCX


I need to pass in the file name in my return but not sure how to do this.

Please see code below:

string[] fileTypes = WebConfigurationManager.AppSettings["allowedFiletypes"].Split(','); //read filetypes from webconfig with split

if (File != null) // this finds overall null
{
foreach (var fl in File) // loop through every File
{
if (fl != null) //Finds induvidual null
{
var extension = new FileInfo(fl.FileName).Extension.ToUpper(); //variable extension equals to getting user file extension they upload
if (!fileTypes.Contains(extension)) //gets the file extension variable that someone uploads on form through split
{
yield return new ValidationResult(string.Format("Invalid file extension for file..", (fl.FileName)));

}

Answer

You're using String.Format, so just throw {0} into the format string where you want the file name: String.Format("Invalid file extension for uploaded file {0}", fl.FileName)

See documentation: https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx