C#:註冊元件 (cmd)

weixin_34037977發表於2017-03-05
    public class ComRegistor
    {
        public static string classID = "CLSID\\{479A1AAC-C148-40BB-9868-A9773DA66AF9}\\";//SWFToImage元件註冊ID

        /// <summary>
        /// 註冊元件
        /// </summary>
        /// <param name="fileFullName">檔案完整路徑</param>
        /// <param name="dllName">動態庫名</param>
        public static bool Register(string fileFullName, string dllName)
        {
            bool rev = false;
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                p.StandardInput.WriteLine(@"DELETE " + fileFullName + @" %windir%\system32");
                p.StandardInput.WriteLine(@"COPY " + fileFullName + @" %windir%\system32");
                p.StandardInput.WriteLine(@"regsvr32 /s %windir%\system32\" + dllName);
                p.StandardInput.WriteLine("exit");
                string ReturnInfo = p.StandardOutput.ReadToEnd();
                p.Close();
                rev = true;
            }
            catch (Exception e)
            {
                rev = false;
            }

            return rev;
        }
        /// <summary>
        /// 判別某一元件是否已註冊
        /// </summary>
        /// <returns></returns>
        public static bool IsRegister(string classID)
        {
            bool result = false;
            RegistryKey rkTest = Registry.ClassesRoot.OpenSubKey(classID);
            if (rkTest != null)
            {
                result = true;
            }
            return result;
        }

        /*
         
                if (!ComRegistor.IsRegister(ComRegistor.classID))
                {
                    if (File.Exists(System.Environment.SystemDirectory + Path.DirectorySeparatorChar + "SWFToImage.DLL") == true)
                    {
                        File.Delete(System.Environment.SystemDirectory + Path.DirectorySeparatorChar + "SWFToImage.DLL");
                    }

                    
                    ComRegistor.Register(Application.StartupPath + @"\RegSvr\SWFToImage.Dll", "SWFToImage.Dll");

                    if (!ComRegistor.IsRegister(ComRegistor.classID))
                        MessageBox.Show("COM元件註冊失敗");
                }
         */
    }

 

相關文章