• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 661
  • Last Modified:

How to Obtain the file extension using asp:FileUpload

Hi All,

I am using the asp.net control asp:FileUpload and c# in my code behind based on MS' example here http://msdn.microsoft.com/en-us/library/aa479405.aspx .

Though, I am going to rename the file using the user's session id for uniqueness but I need to then make sure that the file's correct extension is added back onto my .SaveAs argument.

Please could anyone suggest how this could be achieved?

Many thanks,

<%@ Page Language="C#" %>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
        if (FileUpload1.HasFile)
                     string strSession;
                strSession = Session.SessionID;
                FileUpload1.SaveAs("C:\\Uploads\\" + 
                Label1.Text = "File name: " +
                     FileUpload1.PostedFile.FileName + "<br>" +
                     FileUpload1.PostedFile.ContentLength + " kb<br>" +
                     "Content type: " +
            catch (Exception ex)
                Label1.Text = "ERROR: " + ex.Message.ToString();
            Label1.Text = "You have not specified a file.";

Open in new window

1 Solution
David H.H.LeeCommented:
Hi rito1,
Try this:
string strext=System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower;
FileUpload1.SaveAs("C:\\Uploads\\" +  strSession + strext);

More details for asp upload control:
rito1Author Commented:
Excellent, thanks. Rit
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now