Get File Extension from File Upload in C#

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.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="GetFileExtension.Index" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8.   
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.         <div>  
  12.             <asp:FileUpload ID="FileUp" runat="server" /><br /><br />  
  13.             <asp:Button ID="BtnGetExtension" runat="server" Text="Get Extension" /><br />  
  14.             <asp:Label ID="LblExtension" runat="server" style="color:red"></asp:Label>  
  15.         </div>  
  16.     </form>  
  17. </body>  
  18.   
  19. </html>  
We will write code to get the extension of the file uploaded. Write the following code in theIndex.aspx.cs file.
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Web;  
  5. usingSystem.Web.UI;  
  6. usingSystem.Web.UI.WebControls;  
  7. namespaceGetFileExtension  
  8. {  
  9.     public partial class Index: System.Web.UI.Page  
  10.     {  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.         }  
  14.         protected void BtnGetExtension_Click(object sender, EventArgs e)  
  15.         {  
  16.             if (FileUp.HasFile)  
  17.             {  
  18.                 stringInputFile = string.Empty;  
  19.                 InputFile = System.IO.Path.GetExtension(FileUp.FileName);  
  20.                 LblExtension.Text = "The extension of the file is: " + InputFile;  
  21.             }  
  22.             else  
  23.             {  
  24.                 LblExtension.Text = "Please upload a file!!";  
  25.             }  
  26.         }  
  27.     }  
  28. }  
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.

 

Ebook Download
View all
Learn
View all