使用c#检查原始文件类型

时间:2016-02-29 12:00:04

标签: c# mime-types

我创建程序来检查文件是否有原始扩展名。 对于前者File.txt是原始文件,然后更改为File.jpeg,然后如何知道原始文件扩展名。

我的代码段是......

string filename = openFileDialog1.FileName;
        string originalFileExt = Path.GetExtension(filename);
        string type = ScanFileForMimeType(filename);
        MessageBox.Show("Mime type : " + type);

        if (type == "application/octet-stream")
        {
            type = System.Web.MimeMapping.GetMimeMapping(filename);
            MessageBox.Show(type + "");
        }

        RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + type, false);
        object value = key != null ? key.GetValue("Extension", null) : null;
        string result = value != null ? value.ToString() : string.Empty;
        MessageBox.Show("File Extension : " + result);

private static string ScanFileForMimeType(string fileName)
    {
        try
        {
            byte[] buffer = new byte[256];
            //using (FileStream fs = new FileStream(fileName, FileMode.Open))
            //{
            //    int readLength = Convert.ToInt32(Math.Min(256, fs.Length));
            //    fs.Read(buffer, 0, readLength);
            //}

            UInt32 mimeType = default(UInt32);
            FindMimeFromData(0, null, buffer, 256, null, 0, ref mimeType, 0);
            IntPtr mimeTypePtr = new IntPtr(mimeType);
            string mime = Marshal.PtrToStringUni(mimeTypePtr);
            Marshal.FreeCoTaskMem(mimeTypePtr);

            if (string.IsNullOrEmpty(mime))
                mime = "application/octet-stream";
            return mime;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

但我没有像.docx,.pptx等那样得到mime类型的MS Office文件。

0 个答案:

没有答案
相关问题