Let us start with a sample demo. Open Visual Studio. Create one empty web application. Add a web form. Write the following HTML mark up in the page.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="GetFileExtension.Index" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <title></title>
- </head>
-
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:FileUpload ID="FileUp" runat="server" /><br /><br />
- <asp:Button ID="BtnGetExtension" runat="server" Text="Get Extension" /><br />
- <asp:Label ID="LblExtension" runat="server" style="color:red"></asp:Label>
- </div>
- </form>
- </body>
-
- </html>
We will write code to get the extension of the file uploaded. Write the following code in theIndex.aspx.cs file.
- using System;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- namespaceGetFileExtension
- {
- public partial class Index: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void BtnGetExtension_Click(object sender, EventArgs e)
- {
- if (FileUp.HasFile)
- {
- stringInputFile = string.Empty;
- InputFile = System.IO.Path.GetExtension(FileUp.FileName);
- LblExtension.Text = "The extension of the file is: " + InputFile;
- }
- else
- {
- LblExtension.Text = "Please upload a file!!";
- }
- }
- }
- }
We have specified a condition to check if there is no file uploaded and the user tries to click the button, then an appropriate error message should be displayed in this scenario. Let us run the application and check the output.
We got the correct extension of the file uploaded previously. In case the user directly clicks the button without uploading the file then the below error should appear.