简体   繁体   English

如何在 C# 中找到文件的扩展名?

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

In my web application (asp.net,c#) I am uploading video file in a page but I want to upload only flv videos.在我的 web 应用程序(asp.net,c#)中,我在页面中上传视频文件,但我只想上传 flv 视频。 How can I restrict when I upload other extension videos?上传其他扩展视频时如何限制?

Path.GetExtension Path.GetExtension

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

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.前 5/6 个索引会告诉您文件类型。 In case of FLV its 70, 76, 86, 1, 5 .在 FLV 的情况下,它的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.如果isAllowed等于true那么它的 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......"在 FLV 的情况下,它的“FLV ......”

content.StartsWith("FLV")

At the server you can check the MIME type, lookup flv mime type here or on google.在服务器上,您可以检查 MIME 类型,在此处或在 google 上查找 flv mime 类型。

You should be checking that the mime type is您应该检查 mime 类型是否为

video/x-flv

If you were using a FileUpload in C# for instance, you could do例如,如果您在 C# 中使用 FileUpload,您可以这样做

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

I'm not sure if this is what you want but:我不确定这是否是您想要的,但是:

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

Or:要么:

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

In addition, if you have a FileInfo fi , you can simply do:此外,如果您有FileInfo fi ,您可以简单地执行以下操作:

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....它将保存文件的扩展名(注意:它将包含. ,因此上述结果可能是: .jpg .txt ,依此类推......

EndsWith() 以。。结束()

Found an alternate solution over at DotNetPerls that I liked better because it doesn't require you to specify a path.DotNetPerls上找到了一个我更喜欢的替代解决方案,因为它不需要您指定路径。 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);
        }
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上述方法适用于 Firefox 和 IE,我可以查看所有类型的文件,如 zip、txt、xls、xlsx、doc、docx、jpg、png

but when i try to find the extension of file from googlechrome , i failed.但是当我尝试从 googlechrome 找到文件的扩展名时,我失败了。

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

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.迟早有人会绕过它并上传他们喜欢的任何内容。

You can check .flv signature.您可以检查 .flv 签名。 You can download specification here:您可以在此处下载规范:

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

See "The FLV header" chapter.请参阅“FLV 标头”一章。

This solution also helps in cases of more than one extension like "Avishay.student.DB"此解决方案还有助于解决多个扩展名(如“Avishay.student.DB”)的情况

                FileInfo FileInf = new FileInfo(filePath);
                string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");
private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}

Path.GetExtension(file.FileName)) will get you the file name Path.GetExtension(file.FileName))将为您获取文件名

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.形成一个名为 test.txt 的文本文件并在 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.按预期返回true,文件名扩展名是name。

Hope this helps someone :).希望这可以帮助某人:)。

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# 在 C# 中获取文件扩展名

I Hope That Helps:-)!我希望这会有所帮助:-)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM