Running CMD as administrator with an argument from C#

后端 未结 5 2193
一向
一向 2020-12-10 16:54

I want to run cmd.exe as administrator with arguments from C# in order to prevent a UAC popup. This is necessary in order to use it as an automated installation

5条回答
  •  心在旅途
    2020-12-10 17:50

    I have been using this code:

            string[] commands = File.ReadAllLines(commandFile);
            foreach (string command in commands)
            {
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.WorkingDirectory = @"C:\Windows\System32";
                startInfo.FileName = "cmd.exe";
                startInfo.Arguments = "/user:Administrator \"cmd /K " + command + "\"";
                process.StartInfo = startInfo;
                process.Start();
            }
    

    As you can see: Trying this code from 'Run' in VS will not give admin, But if you compile this program and run it externally as admin it will. I used this batch file to test privilege level.

    @echo off
    goto check_Permissions
    
    :check_Permissions
    echo Administrative permissions required. Detecting permissions...
    
    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Administrative permissions confirmed.
    ) else (
        echo Failure: Current permissions inadequate.
    )
    
    pause >nul
    

提交回复
热议问题