FileUpload get file extension

CsharpBeginner picture CsharpBeginner · Nov 29, 2011 · Viewed 54.1k times · Source

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.";
}

Answer

jrb picture jrb · Nov 29, 2011
FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;