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

发布于 2024-08-13 20:57:19 字数 70 浏览 2 评论 0原文

在我的网络应用程序(asp.net,c#)中,我正在页面中上传视频文件,但我只想上传 flv 视频。如何限制上传其他扩展视频?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

后来的我们 2024-08-20 20:57:19

Path.GetExtension

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

Path.GetExtension

string myFilePath = @"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
独守阴晴ぅ圆缺 2024-08-20 20:57:19

您可以简单地读取文件流,

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

前 5/6 索引将告诉您文件类型。对于 FLV,其值为 70, 76, 86, 1, 5

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

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

如果 isAllowed 等于 true 则其 FLV。

读取文件的内容

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

前两个/三个字母将告诉您文件类型。
如果是 FLV,则为“FLV......”

content.StartsWith("FLV")

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")
伪装你 2024-08-20 20:57:19

在服务器上,您可以检查 MIME 类型,在此处或在 google 上查找 flv mime 类型。

您应该检查 mime 类型是否为

video/x-flv

如果您在 C# 中使用 FileUpload 例如,您可以这样做

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

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"
绝不服输 2024-08-20 20:57:19

此外,如果您有一个 FileInfo fi,您可以简单地执行以下操作:

string ext = fi.Extension;

它会保存文件的扩展名(注意:它将包含 .,因此上面的结果可能是:.jpg .txt,依此类推......

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

红衣飘飘貌似仙 2024-08-20 20:57:19
string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);

上述方法适用于 Firefox 和 IE:我可以查看所有类型的文件,如 zip、txt、xls、xlsx、doc、docx、jpg、png。

但是当我尝试从 Google Chrome 中查找文件扩展名时,我失败了。

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.

忘你却要生生世世 2024-08-20 20:57:19

我不确定这是否是您想要的,但是:

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

或者:

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

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

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

Or:

Path.GetExtension(@"c:\test.flv")
喜你已久 2024-08-20 20:57:19

EndsWith()< /strong>

DotNetPerls 找到了一个替代解决方案,我更喜欢它,因为它不需要你指定一个路径。这是一个示例,我在自定义方法的帮助下填充了一个数组

        // 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);
        }

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);
        }
过度放纵 2024-08-20 20:57:19

值得一提的是如何在获取扩展的同时删除扩展:

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

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

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
深巷少女 2024-08-20 20:57:19
private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}
private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}
若相惜即相离 2024-08-20 20:57:19

您将无法限制用户在客户端上传的文件类型[*]。您只能在服务器端执行此操作。如果用户上传了错误的文件,您将只能在文件上传后才能识别。没有可靠且安全的方法来阻止用户上传他们想要的任何文件格式。

[*] 是的,您可以在开始上传之前执行各种巧妙的操作来检测文件扩展名,但不要依赖它。迟早有人会绕过它并上传他们喜欢的任何内容。

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.

趁微风不噪 2024-08-20 20:57:19

您可以检查 .flv 签名。您可以在此处下载规范:

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

请参阅“FLV 标头”一章。

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

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

See "The FLV header" chapter.

场罚期间 2024-08-20 20:57:19

该解决方案还有助于解决多个扩展名(例如“Avishay.student.DB”)的情况

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

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), "");
我要还你自由 2024-08-20 20:57:19

Path.GetExtension(file.FileName)) 将为您提供文件名,

如果有人需要测试和获取扩展名或名称,我还会共享测试代码。

形成一个名为 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));

        }

按预期返回 true,文件扩展名是 name。

希望这对某人有帮助:)。

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

凑诗 2024-08-20 20:57:19

我知道这是一个相当老的问题,但这里有一篇关于获取文件扩展名以及更多值的好文章:

在 C# 中获取文件扩展名

我希望有帮助:-)!

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 :-)!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文