Categories
Asp, Asp.net

File Upload Extension Check In ASP.NET

File Upload Extension Check In ASP.NET

In this tutorial we will check the file extension in FILE UPLOAD control in ASP.NET.We can Check the File Extension and if check is false, message will be displayed accordingly.

Design Page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
 width: 100%;
 }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" cellpadding="0" cellspacing="0" class="auto-style1" style="width: 900px">
<tr>
<td>Image</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Upload" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Code View:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected Boolean CheckFileType(string FileName)
    {
        string Ext = System.IO.Path.GetExtension(FileName);

        switch (Ext.ToLower())
        {
            case (".gif"):
                { return true; }
            case (".png"):
                { return true; }
            case (".jpg"):
                { return true; }
            case (".jpeg"):
                { return true; }
            default:
            { return false; }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Boolean Check = CheckFileType(FileUpload1.FileName);
        if (Check == false)
        {
    ScriptManager.RegisterStartupScript(this, this.GetType(), "StartUpScript2", "alert('Invalid File Extension')", true);
        }
    }
}

Comments are closed.