C#通過代碼注冊COM組件


 

 

using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace ChuckLu.Utility
{
    public class Cmd
    {
        private Cmd()
        {
        }

        private static readonly Cmd instance = new Cmd();
        public static Cmd Instance
        {
            get { return instance; }
        }

        private string regsvr32 = "regsvr32 -s {0}";//-s 參數指定 regsvr32 安靜運行,在成功注冊/反注冊DLL文件的前提下不顯示結果提示框。

        public void Regsvr32(string fileName)
        {
            string strcmd = string.Format(regsvr32, fileName);
            Execute(strcmd);
        }

        /// <summary>
        /// 使用cmd執行命令
        /// </summary>
        /// <param name="strCmd"></param>
        /// <returns></returns>
        private void Execute(string strCmd)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo()
            {
                FileName = "cmd.exe",
                UseShellExecute = false,
                RedirectStandardOutput = false,
                CreateNoWindow = true,
                Arguments = "/c " + strCmd
            };

            Process myProcess = new Process()
            {
                StartInfo = processStartInfo
            };

            myProcess.Start();

            myProcess.Close();
        }

        /// <summary>
        /// COM組件是否已經被注冊
        /// </summary>
        /// <param name="clsid"></param>
        /// <returns></returns>
        public bool IsRegistered(String clsid)
        {

            //參數檢查
            Debug.Assert(!String.IsNullOrEmpty(clsid), "clsid 不應該為空");

            //設置返回值
            Boolean result = false;
            //檢查方法,查找注冊表是否存在指定的clsid
            String key = String.Format(@"CLSID\{{{0}}}", clsid);
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(key);
            if (regKey != null)
            {
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 反注冊
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public Boolean UnRegister(String file)
        {
            //參數檢查
            Debug.Assert(!String.IsNullOrEmpty(file), "file 不應該為空");
            //設置返回值
            Boolean result = false;
            //檢查方法,查找注冊表是否存在指定的clsid
            string fileFullName = "\"" + file + "\"";
            Process p = Process.Start("regsvr32", fileFullName + " /s /u");
            if (p != null && p.HasExited)
            {
                Int32 exitCode = p.ExitCode;
                if (exitCode == 0)
                {
                    result = true;
                }
            }
            return result;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM