简体   繁体   中英

Type.GetTypeFromProgID() returns null, but New-Object works in Powershell

I'm trying to create an instance of the COM object Microsoft.Update.AutoUpdate in C#. This works in PowerShell:

$AutoUpdates = New-Object -ComObject "Microsoft.Update.AutoUpdate"

However, this doesn't work in C#:

var autoUpdateClass = Type.GetTypeFromProgID("Microsoft.Update.Auto­Update");
// var autoup = Activator.CreateInstance(autoUpdateClass) as IAutomaticUpdates;

In this case, autoUpdateClass is null. Is there any way to activate an instance of this class? Maybe I have to manually specify the DLL, or ensure the correct bitness of my process?

A working alternative would be to add a reference to WUApiLib.dll , and setting "Embed Interop Types" to false. Then I can just do new AutoUpdateClass() . The drawback is that I then have an additional Interop.WUApiLib.dll , and also people recommend to "never do this" . Any way, I'd like to know why GetTypeFromProgID fails here.

Because you have a special unicode character between "Auto" and "Update" that you probably don't have in your powershell script, if you paste your code into notepad it will display this:

在此处输入图像描述

PS: more and more people have these kind of hidden char issues these days, not sure why...

It is possible to have an Exception. Check with the following code:

try
{
    var autoUpdateClass = Type.GetTypeFromProgID("Microsoft.Update.Auto­Update", true);
}
catch(Exception e)
{
   //check if any exception occured
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM