Thursday, February 12, 2009

How to Register DLLs in C#

The Regsvr32 tool is used to register or un-register DLL or OCX files.

Usage:
Regsvr32 [/u] [/s] [/n] [/i[:cmdline]] dll_name
/u – un-register server
/s – to run silently without display any message boxes
dll_name – indicates the path and file name of the DLL to register. More than one DLL is allowed in this command.

Example:
regsvr32 C:\example.ocx
regsvr32 /u C:\example.ocx



Sometimes we need to register DLLs programmatically, the codes below will show you how to invoke the regsvr32.exe and register a dll file in C#.

using System.Diagnostics;

public static void registerDLL(string dllPath)
{
  try {
    //'/s' : indicates regsvr32.exe to run silently.
    string fileinfo = "/s" + " " + "\"" + dllPath + "\"";

    Process reg = new Process();
    reg.StartInfo.FileName = "regsvr32.exe";
    reg.StartInfo.Arguments = fileinfo;
    reg.StartInfo.UseShellExecute = false;
    reg.StartInfo.CreateNoWindow = true;
    reg.StartInfo.RedirectStandardOutput = true;
    reg.Start();
    reg.WaitForExit();
    reg.Close();
  }
  catch(Exception ex) {
    MessageBox.Show(ex.Message);
  }
}


Hope this will help.

5 comments:

Anonymous said...

Nice piece of code....

Thanks

Anonymous said...

Thanks for the code snippet !

First time I used PInvoke to
do register a COM dll.
Now I can use pure C#.

Claudio said...

Seems to be simple but in Windows7 you need to claim administrative privileges otherwise regsvr32 fails. How can you do that?

scrip on July 6, 2011 at 4:57 PM said...

How can we incorporate threading in this example e.g. you have over a hundred DLLS that you want to register.

Anonymous said...

I will try your code, it seems very good!
Thanks!

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template