Introduction
In this article we will show you how to execute a command in a command prompt also with Administrative Privilege using C# code. Since it is a demo application we are just going to execute a very simple command, "mspaint.exe", that will open Paint. By using this concept you can easily run any command you want to run in cmd by just using the C# code.
I would like to tell you one thing, that at least you should have some basic knowledge of the "ProcessStartInfo" class and the "Process" class.
If not then no need to worry, you can get it very easily on:
http://www.c-sharpcorner.com/UploadFile/2d2d83/how-to-start-a-process-like-cmd-window-using-C-Sharp/
Procedure
Step 1
Create a New “Windows Form Application” in Visual Studio and name it as you choose (I named it WriteCmdDemo).
Now a new form is created.
Step 2
Add a Button Control to your form and resize the window. Your form will look like this:
Step 3
Navigate to the code (Form1.cs) file and add the following two using directives to your project:
- using System.Diagnostics;
- using System.IO;
Step 4
Now just navigate to the Button control Click Event that you added to your project and add the following code:
- private void buttonOpenPaint_Click(object sender, EventArgs e)
- {
- ProcessStartInfo info = new ProcessStartInfo();
- info.RedirectStandardError = true;
- info.RedirectStandardInput = true;
- info.RedirectStandardOutput = true;
-
- info.UseShellExecute = false;
-
- info.CreateNoWindow = true;
-
-
-
-
-
-
- info.WorkingDirectory = @"C:\Windows\System32";
-
-
- info.FileName = @"C:\Windows\System32\cmd.exe";
- info.Verb = "runas";
-
-
- Process pro = new Process();
- pro.StartInfo = info;
- pro.Start();
-
-
- StreamWriter sw = pro.StandardInput;
-
-
- if (sw.BaseStream.CanWrite)
- {
- try
- {
-
-
-
- sw.WriteLine("mspaint.exe");
-
-
- sw.WriteLine("exit");
-
-
- MessageBox.Show("Ms-Paint is going to
- Open!!!");
-
- }
-
- catch (Exception ex)
- {
-
-
- MessageBox.Show("An Error Occured Please
- try again Later!");
- }
- }
- }
Step 5
Now compile and run your code, when you click on "Open Paint" the Microsoft Paint will be opened.
If you have any query regarding anything in this article then you can reply.
That's all for this article. I am embedding the source file so you can go through it.
Thank You.