Use PowerShell with C# to get any file ‘ContentType’

Here’s an example of how you can use a piece of C# code to create an Static method for getting a file ‘ContentType’.  It just took me a few minutes to look for the sample C# code in the internet that would give me the expected result.

I modify the C# code from this blog ( http://codeasp.net/blogs/raghav_khunger/microsoft-net/531/how-to-get-content-type-of-a-file-in-c ) to create my own “”GetContentType” static method in my PowerShell script.


$CSharpCode = @"
using System;
using Microsoft.Win32;
public class Win32file
{
  public static string GetContentType(string getfileName)
  {
    string contentType = "application/octetstream";
    string ext = System.IO.Path.GetExtension(getfileName).ToLower();

    RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(ext);

    if (registryKey != null && registryKey.GetValue("Content Type") != null)

    contentType = registryKey.GetValue("Content Type").ToString();

    return contentType;
  }
}
"@
Add-Type -TypeDefinition $CSharpCode

Usage: [Win32file]::GetContentType(“C:\Temp\GraphicImage.png“)

Result: image/png

Now, this piece of code serve a purpose, and I’m going to be shown it in my next blog post on “How to import a Document into a table BLOB field?”.  YES!! Using PowereShell and much easier than using SSIS.

Stay tuned!

%d bloggers like this: