FileUpload get file extension

57,146

Solution 1

"Path" am I missing a using statement?

You have to add

using System.IO; 

to the list of namespaces

Solution 2

FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;

Solution 3

Use this code:

string extension=System.IO.Path.GetExtension(file1.FileName);

Solution 4

The code you have provided looks fine (and works on my machine).

The only thing I can see that you might be missing is the using statement for System.IO.

Share:
57,146
CsharpBeginner
Author by

CsharpBeginner

Building my first site in charp. Its been a crazy journy so far.

Updated on July 15, 2020

Comments

  • CsharpBeginner
    CsharpBeginner almost 4 years

    I'm trying to upload a file and change its name below. I need to get the file extension. The code below has a underline under "Path" am I missing a using statement? Or what is the correct syntax for what I'm doing?

    if (FileUpload1.HasFile)
    try
    {
        var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);                    
    
        var newName = DateTime.Now.ToLongDateString();
        //Map path to folder
        string realpath = Server.MapPath("Pictures\\") + Guid.NewGuid() + FileExtension;                      
    
        FileUpload1.SaveAs(realpath);
    
        Label1.Text = "File name: " +
            FileUpload1.PostedFile.FileName + "<br>" +
            FileUpload1.PostedFile.ContentLength + " kb<br>" +
            "Content type: " +
            FileUpload1.PostedFile.ContentType;
    }
    catch (Exception ex)
    {
        //Handle the error
        throw ex;
    }
    else
    {
        Label1.Text = "You have not specified a file.";
    }
    
  • Arun Prasad E S
    Arun Prasad E S about 7 years
    Thanks very much.