簡體   English   中英

當Verb =“runas”時設置ProcessStartInfo.EnvironmentVariables

[英]Set ProcessStartInfo.EnvironmentVariables when Verb=“runas”

我正在開發一個C#應用程序。

我需要創建變量並將變量傳遞給新進程,我正在使用ProcessStartInfo.EnvironmentVariables來完成它。

新進程必須提升,所以我使用的是Verb =“runas”

var startInfo =  new ProcessStartInfo(command)
{
    UseShellExecute = true,
    CreateNoWindow = true,
    Verb = "runas"
};
foreach (DictionaryEntry entry in enviromentVariables)
{
    startInfo.EnvironmentVariables.Add(entry.Key.ToString(), entry.Value.ToString());
}

問題是根據msdn文檔

必須將UseShellExecute屬性設置為false才能在更改EnvironmentVariables屬性后啟動該進程。 如果UseShellExecute為true,則在調用Start方法時拋出InvalidOperationException

runas變量需要UseShellExecute = true

有沒有辦法同時執行:將進程作為提升運行並設置環境變量?

編輯

我會試着改寫我的問題......

有沒有辦法將參數安全地傳遞給另一個進程,因此只有其他進程才能讀取參數。

它有效,但缺點是它還顯示第二個命令提示符,環境變量僅在啟動過程的上下文中設置,因此設置不會傳播到整個框。

    static void Main(string[] args)
    {
        var command = "cmd.exe";
        var environmentVariables = new System.Collections.Hashtable();
        environmentVariables.Add("some", "value");
        environmentVariables.Add("someother", "value");

        var filename = Path.GetTempFileName() + ".cmd";
        StreamWriter sw = new StreamWriter(filename);
        sw.WriteLine("@echo off");
        foreach (DictionaryEntry entry in environmentVariables)
        {
            sw.WriteLine("set {0}={1}", entry.Key, entry.Value);
        } 
        sw.WriteLine("start /w {0}", command);
        sw.Close();
        var psi = new ProcessStartInfo(filename) {
            UseShellExecute = true, 
            Verb="runas"
        };
        var ps =  Process.Start(psi);
        ps.WaitForExit();
        File.Delete(filename);
    }

有一個更好的答案:您仍然可以使用具有UseShellExecute = true的ProcessStartInfo調用Process.Start(),前提是您調用它的方法已使用[STAThread]屬性標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM