Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileUpload get file extension

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.";
}
like image 437
CsharpBeginner Avatar asked Nov 29 '11 15:11

CsharpBeginner


People also ask

How can I get file extension in PHP?

There are a few different ways to extract the extension from a filename with PHP, which is given below: Using pathinfo() function: This function returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned.

How do you get the extension of a file in react?

To get a filename extension, you can use a combination of split() and pop() methods. The split() method will convert a string into an array of substrings, separated by the character you passed as the method's parameter. And that's how you can get the file extension from a filename.

How do I find the file type?

Right-click the file. Select the Properties option. In the Properties window, similar to what is shown below, see the Type of file entry, which is the file type and extension.


1 Answers

FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;
like image 199
jrb Avatar answered Sep 22 '22 10:09

jrb