How to find the extension of a file in C#?

C#FileFile Extension

C# Problem Overview


In my web application (asp.net,c#) I am uploading video file in a page but I want to upload only flv videos. How can I restrict when I upload other extension videos?

C# Solutions


Solution 1 - C#

Path.GetExtension

string myFilePath = @"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"

Solution 2 - C#

You may simply read the stream of a file

using (var target = new MemoryStream())
{
    postedFile.InputStream.CopyTo(target);
    var array = target.ToArray();
}

First 5/6 indexes will tell you the file type. In case of FLV its 70, 76, 86, 1, 5.

private static readonly byte[] FLV = { 70, 76, 86, 1, 5};

bool isAllowed = array.Take(5).SequenceEqual(FLV);

if isAllowed equals true then its FLV.

OR

Read the content of a file

var contentArray = target.GetBuffer();
var content = Encoding.ASCII.GetString(contentArray);

First two/three letters will tell you the file type.
In case of FLV its "FLV......"

content.StartsWith("FLV")

Solution 3 - C#

At the server you can check the MIME type, lookup flv mime type here or on google.

You should be checking that the mime type is

video/x-flv

If you were using a FileUpload in C# for instance, you could do

FileUpload.PostedFile.ContentType == "video/x-flv"

Solution 4 - C#

I'm not sure if this is what you want but:

Directory.GetFiles(@"c:\mydir", "*.flv");

Or:

Path.GetExtension(@"c:\test.flv")

Solution 5 - C#

string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);

The above method works fine with the Firefox and IE: I am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png.

But when I try to find the extension of file from Google Chrome, I fail.

Solution 6 - C#

In addition, if you have a FileInfo fi, you can simply do:

string ext = fi.Extension;

and it'll hold the extension of the file (note: it will include the ., so a result of the above could be: .jpg .txt, and so on....

Solution 7 - C#

EndsWith()

Found an alternate solution over at DotNetPerls that I liked better because it doesn't require you to specify a path. Here's an example where I populated an array with the help of a custom method

        // This custom method takes a path 
        // and adds all files and folder names to the 'files' array
        string[] files = Utilities.FileList("C:\", "");
        // Then for each array item...
        foreach (string f in files)
        {
            // Here is the important line I used to ommit .DLL files:
            if (!f.EndsWith(".dll", StringComparison.Ordinal))
                // then populated a listBox with the array contents
                myListBox.Items.Add(f);
        }

Solution 8 - C#

It is worth to mention how to remove the extension also in parallel with getting the extension:

var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only

var extension = Path.GetExtension(fileFullName); // Get the extension only

Solution 9 - C#

You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.

[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.

Solution 10 - C#

You can check .flv signature. You can download specification here:

http://www.adobe.com/devnet/flv/

See "The FLV header" chapter.

Solution 11 - C#

private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}

Solution 12 - C#

This solution also helps in cases of more than one extension like "Avishay.student.DB"

                FileInfo FileInf = new FileInfo(filePath);
                string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSurya sasidharView Question on Stackoverflow
Solution 1 - C#JamesView Answer on Stackoverflow
Solution 2 - C#Mukul YadavView Answer on Stackoverflow
Solution 3 - C#Mark DickinsonView Answer on Stackoverflow
Solution 4 - C#CarraView Answer on Stackoverflow
Solution 5 - C#Papun SahooView Answer on Stackoverflow
Solution 6 - C#NoctisView Answer on Stackoverflow
Solution 7 - C#megamaikuView Answer on Stackoverflow
Solution 8 - C#Mohammed NoureldinView Answer on Stackoverflow
Solution 9 - C#ZombieSheepView Answer on Stackoverflow
Solution 10 - C#Marat FaskhievView Answer on Stackoverflow
Solution 11 - C#Aziz NortozhievView Answer on Stackoverflow
Solution 12 - C#avishayView Answer on Stackoverflow