在C#中找出确切的文件类型 [英] Find out exact file type in C#

查看:108
本文介绍了在C#中找出确切的文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,文件具有扩展名和mime类型. 但是,这两个属性不够智能,两个不能确定文件的确切类型.例如,我有一个.exe文件,并将其重命名为两个扩展名.png.因此,如果我尝试以编程方式找出它的类型或mime类型,结果将是images/png.png,但是我想读取文件的标题并找出确切的文件类型.可以使用C#语言进行编程编程吗?

As you know files have extensions and mime types. but these two attributes are not intelligent enough two determine exact type of file. For example I have a .exe file and i rename it's extension two .png. So if I try to find out it's type or mime type programmatically the result will be images/png or .png but I want to read the header of file and find out exact file type. Is it possible programmatically with C# language?

修改

当然,有些问题与我的类似,但是您知道文件以十六进制字符串开头,例如:

Of course some questions are similar to mine but as you know files starts with a hex string, for example :

"JPEG", ".jpg", 0xFF, /*0xD*/ 0xD8, 0xFF, 0xE0, null, null, 0x4A, 0x46, 0x49, 0x46, 0x00

"Graphics Interchange Format 87a", ".gif", 0x47, 0x49, 0x46, 0x38, 0x37, 0x6

文件类型的起始十六进制格式是否相似?

Do file types have similar starting hex format?

推荐答案

您可以尝试检查文件中的某些文件签名或幻数.这是已知文件签名的列表的链接,并且看起来很新:

You can try checking for certain file signatures or magic numbers in the files. Here's the link for list of known file signatures and seems quite up to date:

还有另一种方法.使用 Winista MIME检测器.

There is another way of doing the same. Use Winista MIME Detector.

有一个XML文件mime-type.xml,其中包含有关文件类型和用于标识内容类型的签名的信息.您将需要此文件来创建MimeTypes对象的实例.创建MimeTypes对象后,请调用GetMimeType方法以获取流的MimeType.如果无法确定mime类型,则此方法返回一个空对象.以下代码段演示了该库的使用.

There is one XML file mime-type.xml that contains information about file types and the signatures used to identify the content type. You will need this file to create instance of MimeTypes object. Once you have created MimeTypes object, then call GetMimeType method to get MimeType of the stream. If the mime type could not be determined then a null object is returned from this method. Following code snippet demonstrates use of the library.

示例:

  MimeTypes g_MimeTypes = new MimeTypes("mime-types.xml");
    sbyte [] fileData = null;
    using (System.IO.FileStream srcFile = 
        new System.IO.FileStream(strFile, System.IO.FileMode.Open))
    {
        byte [] data = new byte[srcFile.Length];
        srcFile.Read(data, 0, (Int32)srcFile.Length);
        fileData = Winista.Mime.SupportUtil.ToSByteArray(data);
    }
    MimeType oMimeType = g_MimeTypes.GetMimeType(fileData);

这篇关于在C#中找出确切的文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆