Get file type in .NET

后端 未结 5 1352
野性不改
野性不改 2020-12-02 19:22

How can i get type of file using c#. for example if a file name id \"abc.png\" and type of file will \"PNG Image\" same as third column \"Type\" in window explorer.

5条回答
  •  抹茶落季
    2020-12-02 20:09

    If you do not want to use P/Invoke and rather would like to look at the registry yourself:

    private Dictionary GetRegistryFileTypes()
    {
      Dictionary results = new Dictionary();
    
      using (RegistryKey rootKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Explorer\KindMap"))
        if (rootKey != null)
          foreach (string currSubKey in rootKey.GetValueNames())
            results.Add(currSubKey, rootKey.GetValue(currSubKey).ToString());
    
      return results;
    }
    

    Then you can use the extension as a key to get the Registry data for the extension:

    string fileType = GetRegistryFileTypes()[Path.GetExtension(filePath)];
    
    if (fileType != null && fileType.Length > 0)
      // do whatever here
    

提交回复
热议问题