Saturday, March 1, 2008

Creating a COM object in .Net based on its ProgID

Once you've created a reference to a COM object on your system, how do you go about creating the object? You can't just use CreateObject or new. You have to use a few .Net methods from the System namespace.


--------------------------------------------------------------------------------

Solution: Use GetTypeFromProgID and Activator.CreateInstance.
You can ask for the type using the GetTypeFromProgID method of the Type object. Then use the static method Activator.CreateInstance to create it from the Type.

The COMCreateObject function is static so I usually include it in my NSLibStatic class. The sole purpose of the class is to hold static methods that I write. You can put it anywhere you like.

Then put this method into one of your classes:

///


/// Creates a COM object given it's ProgID.
///

/// The ProgID to create
/// The newly created object, or null on failure.
public static object COMCreateObject (string sProgID)
{
// We get the type using just the ProgID
Type oType = Type.GetTypeFromProgID (sProgID);
if (oType != null)
{
return Activator.CreateInstance(oType);
}

return null;
}

No comments: