[英]How do you register COM assemblies programmatically in C#?
我想從技術上講,它不一定是 COM 組件。 但是,我想包含它,因為這就是我自己搜索它的方式。
目前,我們使用一個批處理文件,通過以下行注冊它們:
c:\windows\microsoft.net\framework\v4.0.30319\regasm.exe c:\Path\To\AssemblyToRegister.dll /codebase /s /tlb
您將如何在 C# 代碼中注冊它,以便我們可以擺脫批處理文件並更好地自動化此過程?
注意:以下代碼需要以管理員身份運行應用程序!
Assembly asm = Assembly.LoadFrom(@"c:\Path\To\AssemblyToRegister.dll");
RegistrationServices regAsm = new RegistrationServices();
bool bResult = regAsm.RegisterAssembly(asm, AssemblyRegistrationFlags.SetCodeBase);
我最初從這個頁面找到了這個答案。 但是,我們遇到了一個問題,它在第三行拋出了一個帶有某個 dll 的異常,並發現表單第 1 行的“LoadFile”應該是“LoadFrom”。 這是我們找到修復程序的 Stack Overflow 問題的鏈接。
這是我的第一次嘗試,這不是最好的方法。 我正在添加以防它在將來對某人有所幫助。
此代碼假定dllLocation
變量中提供了 dll 的絕對路徑。 您可能還必須將 regasm 位置值更改為它安裝在計算機上的任何位置。
string regasmLocation = @"c:\windows\microsoft.net\framework\v4.0.30319\regasm.exe";
try
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = regasmLocation;
// If you want the tlb (type library) created use the following.
//p.StartInfo.Arguments = dllLocation + @" /codebase /s /tlb";
p.StartInfo.Arguments = dllLocation + @" /codebase /s";
p.Start();
// To avoid deadlocks, always read the output stream first and then wait. https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standarderror?view=net-6.0
string standardError = p.StandardError.ReadToEnd();
string standardOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine($"Successfully registered '{dllLocation}'.");
if (!string.IsNullOrWhiteSpace(standardOutput))
{
Console.WriteLine($"Standard Output: \n{standardOutput}");
}
if (!string.IsNullOrWhiteSpace(standardError))
{
Console.WriteLine($"Standard Error: \n{standardError}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
return true;
這是有限的,因為它通過控制台 window 運行 regasm。 這意味着您無法真正處理異常。 我建議用我的其他答案以編程方式進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.