Share via

Issue to netsh command

Scott Huang 3,511 Reputation points
2023-12-31T13:29:21.9+00:00

Hi,

Is the following one correct to run one netsh command running command prompt as the administrator? fld1 below is having one netsh command.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = fld1;
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Anonymous
2024-01-01T02:41:13.26+00:00

Hi @Scott Huang , Welcome to Microsoft Q&A,

Append "/c" to the command line argument, which instructs Command Prompt to execute the command and then terminate.

Please ensure the following:

  1. The application itself must have sufficient permissions to run the netsh command. This usually requires running the application as an administrator.
  2. The netsh command in fld1 must be a valid and correctly formatted command. Please make sure that the commands in fld1 can be executed correctly in the command prompt.
  3. If the user cancels the prompt for administrator privileges, the catch** block will catch the System.ComponentModel.Win32Exception exception, and you can add appropriate handling code there.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c " + fld1; // Use "/c" to run the command and then terminate
startInfo.Verb = "runas";

process.StartInfo = startInfo;

try
{
     process.Start();
     process.WaitForExit();
}
catch (System.ComponentModel.Win32Exception ex)
{
     // Handle exceptions, e.g., if the user cancels the elevation prompt
     // MessageBox.Show(ex.Message);
}

Best Regards,

Jiale


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.