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

14

205

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?

Mach answered 11/12, 2009 at 9:30 Comment(4)
If possible, you want to also check on the client, to avoid unnecessary uploads.Hickson
Yes, but see my answer below - do NOT rely on client side checking - it will be circumvented sooner or later. :)Markhor
The client-side check is not a protection for your server, but a convenience for the user.Hickson
Granted. I'm just advising the OP not to rely on it.Markhor
G
384

Path.GetExtension

string myFilePath = @"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
Gatha answered 11/12, 2009 at 9:32 Comment(7)
This allows someone to just rename any file *.flv and upload it. Depending on what your requirements are, you might want to check the MIME type as well.Pelagic
Does not the MIME type usually get set according to the file name extension?Hickson
@Thilo, you're right, but the extension can be changed without changing the mime content type. The mime type describes the data contained in the file, so it can be handled appropriately see en.wikipedia.org/wiki/MIMEEartha
No, the better way is to check file content. It is necessary to check flv signature.Thallus
Just to add to this since it’s still a popular answer - the MIME type argument is just as insecure as the extension as both can be spoofed. A combination of both checks is probably a reasonable solution but ultimately if security is a concern then there should be more rigourous checks e.g. blocking unsigned files or content sampling.Gatha
This does not all the time behave well in Windows 7.Planchet
@Planchet interesting, in what way? Also which version of .NET?Gatha
C
31

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")
Columbary answered 16/7, 2014 at 5:50 Comment(1)
This should be rated higher. If you really want your application to work and the data is untrusted, you should check the beginning.Saied
E
7

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"
Eartha answered 11/12, 2009 at 9:34 Comment(0)
B
6

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....

Brigittebriley answered 6/4, 2014 at 6:20 Comment(0)
G
6
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.

Galligaskins answered 2/1, 2018 at 11:40 Comment(1)
What's the relation between Firefox, IE, Chrome and C#? The OP is talking about server-side code, nothing about the browser or any type of client code...Blackmun
O
5

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

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

Or:

Path.GetExtension(@"c:\test.flv")
Oliva answered 11/12, 2009 at 9:38 Comment(0)
T
4

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);
        }
Trafalgar answered 8/11, 2016 at 21:51 Comment(0)
B
4

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
Bestial answered 31/5, 2018 at 0:45 Comment(0)
E
3
private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}
Eada answered 19/2, 2021 at 8:18 Comment(2)
You might want to use LastIndexOf in case of file name such as file.new.png. For example: var index_point = attachment_name.LastIndexOf(".") + 1;Cassiopeia
Te get the extension without the period: Path.GetExtension(fileName).TrimStart('.'). Works also if there is no extension.Hermeneutics
M
2

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.

Markhor answered 11/12, 2009 at 9:38 Comment(7)
While he cannot prevent a hacker from uploading what he wants, he should still check on the client side as a convenience to the user. Flash uploaders should be able to check the file type.Hickson
The OP didn't mention Flash uploaders (that is 'uploaders written in Flash', rather than 'uploaders of Flash content'). The question is tagged with asp.net and c# tags, and with those technology choices, the client-side checking is limited and easily defeated. :)Markhor
For a video upload site, he should have something better on the client-side then an HTML upload form. Multi-MB uploads without a progress bar are no fun.Hickson
ok you saying that client side check is not that much good how can i check in server side Mr. ZombieSheepMach
@Hickson - I couldn't agree more, but the question is about an ASP.net upload form. It's up to the OP whether he thinks that's good enough or not.Markhor
@Surya: plenty of answers about server-side checks already on this page.Hickson
@Surya sasidhar - This should get you started... -> msdn.microsoft.com/en-us/library/aa479405.aspxMarkhor
T
2

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

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

See "The FLV header" chapter.

Thallus answered 11/12, 2009 at 9:41 Comment(0)
R
1

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), "");
Richierichlad answered 6/8, 2015 at 7:57 Comment(0)
L
0

Path.GetExtension(file.FileName)) will get you the file name

Im also sharing a test code if someone needs to test and ge the extention or name.

Forming a text file with name test.txt and checking its extention in xUnit.

        [Fact]
        public void WrongFileExtention_returnError()
        {
            //Arrange
            string expectedExtention = ".csv";
            var content = "Country,Quantity\nUnited Kingdom,1";
            var fileName = "test.csv";
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(content);
            writer.Flush();
            stream.Position = 0;

            //Act 
            IFormFile file = new FormFile(stream, 0, stream.Length, "", fileName);
            
            //Assert
            Assert.Equal(expectedExtention, Path.GetExtension(file.FileName));

        }

Return true as the expected and the filename extention is name.

Hope this helps someone :).

Lustrum answered 21/7, 2022 at 6:47 Comment(0)
G
0

I know this is quite an old question but here's a nice article on getting the file extension as well as a few more values:

Get File Extension in C#

I Hope That Helps :-)!

Grantor answered 2/9, 2022 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.