Determine the File Type Using C#

Find out exact file type in C#

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:

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

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.

Example :

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

How can I determine the type of C# file in Visual Studio?

No, I'm afraid not -- not generally. Once created, that's it.

Get file type in .NET

You will need to use the windows API SHGetFileInfo function

In the output structure, szTypeName contains the name you are looking for.

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
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;
};

Note that this is simply the current "Friendly name" as stored in the Windows Registry, it is just a label (but is probably good enough for your situation).

The difference between szTypeName and szDisplayName is described at MSDN:

szTypeName: Null-terminated string that
describes the type of file.

szDisplayName: Null-terminated string
that contains the name of the file as
it appears in the Windows shell, or
the path and name of the file that
contains the icon representing the
file.

For more accurate determination of file type you would need to read the first chunk of bytes of each file and compare these against published file specifications. See a site like Wotsit for info on file formats.

The linked page also contains full example C# code.



Related Topics



Leave a reply



Submit