首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# Visio 二次開發:Web 端啟動繪圖客戶端並自動登入(二)——安裝程式修改系統 PATH 環境變數

     編輯:關於C語言

核心需求:Web JS 呼叫本地程式

JavaScript WScript.Shell.Run 需在系統 PATH 中找到執行檔。安裝時將應用程式目錄加入系統環境變數 PATH。

自定義安裝動作完整代碼


[RunInstaller(true)]
public class InstallAction : Installer
{
    private string virtualRoot = string.Empty;
    private string physicalRoot = string.Empty;
    private Container components = null;

    public InstallAction() { InitializeComponent(); }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        try
        {
            // ... 其他安裝邏輯 ...
            UpdatePathEnvironment(); // 修改 PATH
        }
        catch (Exception ex)
        {
            WriteLog(ex.Message + "\r\n" + ex.StackTrace);
        }
    }

    private void UpdatePathEnvironment()
    {
        string registerKey = "SYSTEM\\ControlSet001\\Control\\Session Manager\\Environment";
        string key = "Path";
        
        RegistryKey regKey = Registry.LocalMachine.OpenSubKey(registerKey);
        string result = regKey.GetValue(key).ToString();
        
        // 避免重複添加
        if (result.IndexOf(physicalRoot) < 0)
        {
            result += string.Format(";{0}", physicalRoot);
        }
        
        // 需寫入權限重新開啟
        regKey = Registry.LocalMachine.OpenSubKey(
            registerKey, 
            RegistryKeyPermissionCheck.ReadWriteSubTree, 
            RegistryRights.SetValue);
        regKey.SetValue(key, result);
    }
    
    // ... 其他方法 ...
}

關鍵技術細節

  • 登錄路徑:SYSTEM\ControlSet001\Control\Session Manager\Environment\Path
  • 權限提升:RegistryKeyPermissionCheck.ReadWriteSubTree + RegistryRights.SetValue
  • 去重邏輯:IndexOf 檢查避免重複路徑
  • 格式規範:路徑間以分號 ; 分隔
  • 即時生效:新啟動進程自動繼承更新後的 PATH

注意事項

  • 需系統管理員權限執行安裝程式
  • 修改機器層級 PATH 影響所有使用者
  • 建議安裝完成提示使用者重新啟動瀏覽器/電腦
  • 解除安裝時應移除對應路徑(略)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved