Run command as Admin c#

Asked

Viewed 717 times

1

I’ll get right to the point! I have a C# application and need to execute a command in Cmd with Admin privilege. I need to activate SQL Server if it is stopped.

public List<Atendimento> Pesquisar()
    {
        try
        {
            using (CasaVipEntities objEntity = new CasaVipEntities())
            {
                var result = objEntity.Atendimento.GroupBy(c => c.Cliente).ToList();
                return result.SelectMany(x => x).ToList();

            }
        }
        catch (System.Data.Entity.Core.EntityException) 
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

            Process myProcess = new Process();

            myProcess.StartInfo.FileName = "cmd.exe";
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.RedirectStandardInput = true;

            myProcess.Start();

            StreamWriter myStreamWriter = myProcess.StandardInput;
            myStreamWriter.WriteLine("net start MSSQL$SQLEXPRESS");
            myStreamWriter.Close();
            myProcess.WaitForExit();
            myProcess.Close();

        }

I don’t know why you are not activating SQL Server. If I open cmd normally and type the command it activates, but the application does not. I thank you in advance!

2 answers

0

Try placing the following command:

myProcess.StartInfo.Verb = "runas";
  • Unsuccessful. The prompt opens but executes the command

0

Try to do alternatively, calling the prompt already with the command to run:

  Process myProcess = new Process();

  myProcess.StartInfo.FileName = "cmd.exe";
  myProcess.StartInfo.UseShellExecute = false;
  myProcess.StartInfo.Verb = "runas";
  myProcess.StartInfo.Arguments = "/c \"net start MSSQL$SQLEXPRESS\"";

  myProcess.Start();
  myProcess.WaitForExit();
  // myProcess.Close(); -- não é necessário

This way, the parameter /c will already inform the command to be executed. And the entry RunAs will indicate that the process requires upgrade.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.