Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file type in .NET

Tags:

c#

.net

file

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.

like image 887
Firoz Avatar asked Sep 17 '09 08:09

Firoz


2 Answers

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

private Dictionary<string, string> GetRegistryFileTypes()
{
  Dictionary<string, string> results = new Dictionary<string, string>();

  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
like image 120
RooiWillie Avatar answered Sep 19 '22 00:09

RooiWillie


You'll need to P/Invoke to SHGetFileInfo to get file type information. Here is a complete sample:

using System;
using System.Runtime.InteropServices;

static class NativeMethods
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
        public IntPtr hIcon;
        public int iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    };

    public static class FILE_ATTRIBUTE
    {
        public const uint FILE_ATTRIBUTE_NORMAL = 0x80;
    }

    public static class SHGFI
    {
        public const uint SHGFI_TYPENAME = 0x000000400;
        public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
    }

    [DllImport("shell32.dll")]
    public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}

class Program
{
    public static void Main(string[] args)
    {
        NativeMethods.SHFILEINFO info = new NativeMethods.SHFILEINFO();

        string fileName = @"C:\Some\Path\SomeFile.png";
        uint dwFileAttributes = NativeMethods.FILE_ATTRIBUTE.FILE_ATTRIBUTE_NORMAL;
        uint uFlags = (uint)(NativeMethods.SHGFI.SHGFI_TYPENAME | NativeMethods.SHGFI.SHGFI_USEFILEATTRIBUTES);

        NativeMethods.SHGetFileInfo(fileName, dwFileAttributes, ref info, (uint)Marshal.SizeOf(info), uFlags);

        Console.WriteLine(info.szTypeName);
    }
}
like image 30
bobbymcr Avatar answered Sep 21 '22 00:09

bobbymcr