C# Check File Extension In Array Of Valid Extension
Posted by in CSharp December 4, 2011 1 Comment

Assume that we’re building an upload function that allow people be able to upload either photo or video to server. Before storing the uploaded file to hard drive of web server, we need to verify that file extension is valid. And file extension validation is the first and important step in the checking process.

This post provides a simple function (with 2 input parameters: extension and type string) that validate file extension for video and photo. And each part will have an array of accepted extensions.

C# Check File Extension

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class check_valid_extension : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int is_valid = 0;
 
        is_valid = chkValidExtension(".jpg", "photo");
 
        if (is_valid == 1)
        {
            Response.Write("The file extension is valid");
        }
        else if (is_valid == 0)
        {
            Response.Write("The file extension is not valid");
        }
    }
 
    public int chkValidExtension(string ext, string type)
    {
        if (type == "photo")
        {
            string[] PosterAllowedExtensions = new string[] { ".gif", ".jpeg", ".jpg", ".png" };
            for (int i = 0; i < PosterAllowedExtensions.Length; i++)
            {
                if (ext == PosterAllowedExtensions[i])
                    return 1;
            }
 
            return 0;
        }
        else if (type == "video")
        {
            string[] TrailerAllowedExtensions = new string[] { ".flv", ".asf", ".avi", ".wmv", ".mp4", ".mov", ".3gp", ".m4v", ".3g2" };
            for (int i = 0; i < TrailerAllowedExtensions.Length; i++)
            {
                if (ext == TrailerAllowedExtensions[i])
                    return 1;
            }
 
            return 0;
        }
 
        return 0;
    }
}

First you need to get file extension from the uploaded file and pass it to chkValidExtension function as “ext” parameter and pass “video” or “photo” for “type” parameter depend on your need.

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • http://fertui.angelfire.com/youtube/ youtube videos downloaden

    Thank you for every other informative web site. Where else may just I am getting that type of info written in such a perfect method? I’ve a project that I’m just now working on, and I’ve been on the look out for such information.