使用管理员凭据运行进程

本文关键字:运行 进程 管理员 | 更新日期: 2023-09-27 18:36:22

我已经为此工作了一段时间,经过大量搜索和阅读仍然没有解决方案,它让我发疯。我正在尝试使用"提升"(域管理员)权限启动一个进程。

这是我的代码:

public class StartProcess
{
    private ProcessStartInfo info;
    private SecureString ConvertPassword(string _password)
    {
        SecureString password = new SecureString();
        for (int i = 0; i < _password.Length; i++)
        {
            password.AppendChar(_password[i]);
        }
        return password;
    }
    public void Start(string path, string fileName)
    {
        info = new ProcessStartInfo(fileName);
        info.Domain = "setours";
        info.UserName = "administrator";
        info.Password = ConvertPassword("ServerTotal_2013");
        info.UseShellExecute = false;
        info.WorkingDirectory = path;
        try
        {
            Process.Start(info);
        }
        catch (System.ComponentModel.Win32Exception ex)
        {
            MessageBox.Show(ex.Message + ex.StackTrace);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + ex.StackTrace);
        }
        finally
        {
            //Just for debuggin purpuses
            MessageBox.Show(path + fileName);
        }
    }
}

我正在根据主类中的按钮单击事件调用该函数:

private StartProcess startProcess = new StartProcess();
private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button button = (Button)sender;
        switch (button.Content.ToString())
        {
            case "Contable":
                startProcess.Start("C:''Program Files (x86)''StarSoft GE", "''Contabilidad.exe");
                break;
            case "Planilla":
                break;
            case "Caja y banco":
                break;
            case "Cuentas por pagar":
                break;
            default:
                MessageBox.Show("Unknown process");
                break;
        }
    }

我也尝试过用户模拟,但这似乎也不起作用。我一直在为2个错误而苦苦挣扎:

  1. 找不到指定的路径
  2. 访问被拒绝

其他帖子指出,如果您使用ProcessInfouserpassword参数,则需要将UseShellExecute设置为false 。如果您已将其设置为 false ,不再使用该workingDirectory

有人有任何疑问吗?

使用管理员凭据运行进程

试试这个:

private void RunElevated(string fileName)
{
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.Verb = "runas";
    processInfo.FileName = fileName;
    try
    {
        Process.Start(processInfo);
    }
    catch (Win32Exception)
    {
        //Do nothing. Probably the user canceled the UAC window
    }
}