How to open command prompt and execute a command from C#

-1

If I run this command in the command prompt as an administrator. It do sync the computerclock:

w32tm /resync

But I would need to execute this from my C# winform application and tried to put it in this class. As seen I like to retreive the progress of how the resync went in cmd using: StandardOutput and StandardError

But I receive this error below and I don't know why. I think it has with administrator rights. But I do send the .Verb = "runas"; command which should elevate the permissions.

"The following error occured: access is denied (0x80070005)" enter image description here

        public void SyncDateTime()
        {
            try
            {
                ServiceController serviceController = new ServiceController("w32time");
                if (serviceController.Status != ServiceControllerStatus.Running)
                {
                    serviceController.Start();
                }
                //MessageBox.Show("w32time service is running");
                Process process = new Process();
                process.StartInfo.WorkingDirectory = @"C:\Windows\system32";
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.Arguments = "/k w32tm /resync";
                process.StartInfo.Verb = "runas";

                process.StartInfo.ErrorDialog = false;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;

                bool processStarted = process.Start();
                if (processStarted)
                {
                    //Get the output stream
                    StreamReader outputReader = process.StandardOutput;
                    StreamReader errorReader = process.StandardError;
                    process.WaitForExit();

                    //Display the result
                    string displayText = "Output" + Environment.NewLine + "==============" + Environment.NewLine;
                    displayText += outputReader.ReadToEnd();
                    displayText += Environment.NewLine + "Error" + Environment.NewLine + "==============" +
                    Environment.NewLine;
                    displayText += errorReader.ReadToEnd();
                    MessageBox.Show(displayText);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("unable to sync date time from NTP server" + "__" + exception.ToString());
            }
        }

c#
cmd
asked on Stack Overflow Mar 8, 2019 by Andreas • edited Mar 8, 2019 by Andreas

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0