Type.GetTypeFromProgID() returns null,但 New-Object 在 Powershell 中有效
Type.GetTypeFromProgID() returns null, but New-Object works in Powershell
我正在尝试在 C# 中创建 COM 对象 Microsoft.Update.AutoUpdate
的实例。这适用于 PowerShell:
$AutoUpdates = New-Object -ComObject "Microsoft.Update.AutoUpdate"
但是,这在 C# 中不起作用:
var autoUpdateClass = Type.GetTypeFromProgID("Microsoft.Update.AutoUpdate");
// var autoup = Activator.CreateInstance(autoUpdateClass) as IAutomaticUpdates;
在这种情况下,autoUpdateClass
为空。有什么方法可以激活这个 class 的实例吗?也许我必须手动指定 DLL,或者确保我的进程的正确位数?
一个可行的替代方法是添加对 WUApiLib.dll
的引用,并将 "Embed Interop Types" 设置为 false。那我就可以new AutoUpdateClass()
了。缺点是我再多一个Interop.WUApiLib.dll
,也有人推荐给"never do this"。无论如何,我想知道为什么 GetTypeFromProgID
在这里失败。
有可能出现异常。使用以下代码检查:
try
{
var autoUpdateClass = Type.GetTypeFromProgID("Microsoft.Update.AutoUpdate", true);
}
catch(Exception e)
{
//check if any exception occured
}
因为您在 "Auto" 和 "Update" 之间有一个特殊的 unicode 字符,您的 powershell 脚本中可能没有,如果您将代码粘贴到记事本中,它将显示:
PS: 现在越来越多的人有这种隐藏的字符问题,不知道为什么...
我正在尝试在 C# 中创建 COM 对象 Microsoft.Update.AutoUpdate
的实例。这适用于 PowerShell:
$AutoUpdates = New-Object -ComObject "Microsoft.Update.AutoUpdate"
但是,这在 C# 中不起作用:
var autoUpdateClass = Type.GetTypeFromProgID("Microsoft.Update.AutoUpdate");
// var autoup = Activator.CreateInstance(autoUpdateClass) as IAutomaticUpdates;
在这种情况下,autoUpdateClass
为空。有什么方法可以激活这个 class 的实例吗?也许我必须手动指定 DLL,或者确保我的进程的正确位数?
一个可行的替代方法是添加对 WUApiLib.dll
的引用,并将 "Embed Interop Types" 设置为 false。那我就可以new AutoUpdateClass()
了。缺点是我再多一个Interop.WUApiLib.dll
,也有人推荐给"never do this"。无论如何,我想知道为什么 GetTypeFromProgID
在这里失败。
有可能出现异常。使用以下代码检查:
try
{
var autoUpdateClass = Type.GetTypeFromProgID("Microsoft.Update.AutoUpdate", true);
}
catch(Exception e)
{
//check if any exception occured
}
因为您在 "Auto" 和 "Update" 之间有一个特殊的 unicode 字符,您的 powershell 脚本中可能没有,如果您将代码粘贴到记事本中,它将显示:
PS: 现在越来越多的人有这种隐藏的字符问题,不知道为什么...