LSTANCZYK
9/25/2017 - 1:30 AM

Validate file extension ( .pdf in example ) in MVC project C#.

Validate file extension ( .pdf in example ) in MVC project C#.

using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Areas.Cms.Validation
{
    public class ValidateExtensionAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            HttpPostedFileBase file = value as HttpPostedFileBase;
            if (file != null)
            {
                try
                {
                    string[] AllowedFileExtensions = new string[] { ".pdf" };
                    var filename = file.FileName;
                    return AllowedFileExtensions.Contains(filename.Substring(filename.LastIndexOf('.')));
                }
                catch { }
                return false;
            }
            return true;
        }
    }
}