Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Current Affairs » Shell Commands within C#

Shell Commands within C#

In this article we will examine a few examples for executing shell commands outside of our program using C#.

Author Rank :
Page Views : 372755
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In this article we will examine a few examples for executing shell commands outside of our program using C#. In VB.Net, we can make use of the familiar Shell command to run an executable program. However the Shell function is not available in C#. The Process Class provides access to local and remote processes and enables you to start and stop local system processes.

In our example we will create an example for running the following processes from our program.

  1. Calculator
  2. DOS Batch program - Map a network drive
  3. Internet explorer with a specified URL
  4. Specified Document in Microsoft Word.

C# Application

Our basic application is a Winforms Visual C# application and will consist of a Windows Form with button controls to invoke the processes specified in the list. (The complete code for the application is provided at the bottom of the article).

Add button controls from the toolbox as shown in the figure below.

Figure 1: Basic Windows Form

Calculator

The option to provide a calculator to the end user on the click of a button can be very useful. The calculator program can be invoked from command line using the command "calc".

Add the following code to the event handler for the button's Click event as shown below. Details explaining the code follow the code listing.

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="calc";
proc.Start();

Code Listing: Invoke the calculator from a C# program

We create a new Process and assign the FileName variable to the name of the executable that we want to run. The Start() method of the Process object starts the specified application and assigns it to the process component.

Figure: Calculator is invoked when the Calculator button is clicked.

Map a network Drive

We will invoke a DOS batch script which will map a network drive for us. The DOS command for mapping a drive is as follows:

NET USE <DriveName>: \\<RemoteServer>\<SharedFolder> /User:<Domain>\<UserName> <password> /PERSISTENT:YES

Note : Ensure that the drive mapping is not already in use.

Create a text file containing the above command and Save the file as netdrv.bat. I saved the file in folder c:\dotnetstuff\netdrv.bat.

Here is the format of the command contained in the netdrv.bat file.

NET USE U: \\master\testshare /User:Enterprise\dchoksi passwd /PERSISTENT:YES

Add the following code to the button click event handler of the button labeled "Map Network Drive".

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="c:\\dotnetstuff\\netdrv.bat";
proc.Start();
MessageBox.Show("Map Drive Created");

Code Listing: This code will execute the dos batch file and U:\ is mapped to the remote share \\master\testshare.

Microsoft.com

We will create a button that will take the user to the Microsoft.com web site. This logic can be used to open up a registration form for product registration or to point to online help in Windows forms products.

Add the following code in the button Click event handler :

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments=http://www.microsoft.com;

proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited www.microsoft.com");

Code Listing: Microsoft.com

Note that the code waits for the Internet Explorer process to exit and then proceeds to display the messagebox. This is achieved through the use of the WaitForExit() function of the Process object.

Open a specific document in Microsoft Word.

Add the following code to the button's OnClick event handler.

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="winword";
proc.StartInfo.Arguments="C:\\Dotnetstuff\\TestWordDoc.doc";
proc.Start();

Code Listing : Open specific Word Document

Note that the name of the Word document to open is specified in the Arguments for the StartInfo of the Process.

Complete Code Listing:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace ShellCS_NS
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
public
Form1()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(16, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 72);
this.button1.TabIndex = 0;
this.button1.Text = "Calculator";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button2.Location = new System.Drawing.Point(16, 120);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(112, 72);
this.button2.TabIndex = 1;
this.button2.Text = "Map Network Drive";
this.button2.Click += new System.EventHandler(this.button2_Click);
this.button3.Location = new System.Drawing.Point(168, 24);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(112, 72);
this.button3.TabIndex = 2;
this.button3.Text = "Microsoft.com";
this.button3.Click += new System.EventHandler(this.button3_Click);
this.button4.Location = new System.Drawing.Point(168, 120);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(112, 64);
this.button4.TabIndex = 3;
this.button4.Text = "My Word Document";
this.button4.Click += new System.EventHandler(this.button4_Click);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 213);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button4, this.button3, this.button2, this.button1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
[STAThread]
static void Main()
{
Application.Run(
new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="calc";
proc.Start();
}
private void button2_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="c:\\dotnetstuff\\NETDRV.bat";
proc.Start();
MessageBox.Show("Map Drive Created");
}
private void button3_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments=http://www.microsoft.com;
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited www.microsoft.com");
}
private void button4_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc =
new System.Diagnostics.Process();
proc.EnableRaisingEvents=
false;
proc.StartInfo.FileName="winword";
proc.StartInfo.Arguments="C:\\Dotnetstuff\\TestWordDoc.doc";
proc.Start();
}
}
}

Code Listing: Shellcs.cs

NET USE U: \\master\testshare /User:Enterprise\dchoksi passwd /PERSISTENT:YES

Code Listing : Netdrv.bat

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dipal Choksi
Dipal Choksi has over 10 years of industry experience in team-effort projects and also as an individual contributor. She has been working on the .Net platform since the beta releases of .Net 1.0.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Shell Commands within C# by nang On December 25, 2007
Hi, I use System.Diagnostics.Process.Start ("cmd", @"/c format F:/V:Removable Disk"); to format USB disk, it work. But I have to press Enter. Can I no need press ENTER, it will work Automatically? Any body help!
Reply | Email | Modify 
Re: Shell Commands within C# by deepak On May 25, 2010
Hi,

Did you get the solution for your problem.
I am also facing the same issue. I need to press Enter. Could you please let me know the solution of this problem.

Thanks & Regards,
DK
Reply | Email | Modify 
Re: Re: Shell Commands within C# by deepak On May 25, 2010

Hey,

I have found the solution to pass the enter through c# code. we need to use the Process.StandardInput property which will provide a stream to write all the input.

Please use the following code to format a drive.

// Code

Process
proc = null;

try

{

proc = new Process();

proc.StartInfo.FileName = "cmd.exe";

proc.StartInfo.Arguments = @"/c format g:/q/fs:fat ";

proc.StartInfo.UseShellExecute = false;

proc.StartInfo.RedirectStandardInput = true;

proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;

proc.StartInfo.CreateNoWindow = true;

proc.Start();

// redirect the input to stream writer. 

StreamWriter sw = proc.StandardInput;

// pass the inputs to stream writer ("Enter")

sw.Write("\n\r");

sw.Write("\n\r");

proc.WaitForExit();

Reply | Email | Modify 
It worked!!! Thanks a lot!!! by Arun On December 9, 2008

Hi I am an ASP.Net developer, India, and I needed to use the "net use" command to copy files. It is after visiting this article, my three days of ordeal for this simple file copy operation came to an end. thanks a lot again. Also I would like to show that, to hide the "cmd" window when executing any DOS-based commands, we can use

System.Diagnostics.Process objProcess = new Process();
//// Your code goes here
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//// Your code goes here objProcess.Start();
Using objProcess.WaitForExit() is also recommended.
With thanks
Arun Prasad.K.R -- nithyavidhyaarthi@gmail.com

Reply | Email | Modify 
mapping a drive by rahul On February 5, 2009
hi , i am a student of mca-2nd year ,india and i needed to using "net use" command mapped the server machine and also cannect to server . please give me proper gide or exicuted code for solving this problem
Reply | Email | Modify 
question by bikash On August 15, 2009
sir can you give some idea about how to check the output of shell command executed
example
i want to check the output of  " ping 172.31.100.29"
is there any method for doing, plzzzzzzzzzz give some suggestion
Reply | Email | Modify 
Query_C#.Net by Kshitij On September 9, 2009

This article is very good but I want to run exe of C from C#.Net and that will after opening Dos Prompt and the name of the exe will be given from Window Interface that is what i want to make.
Plz Help.............

Reply | Email | Modify 
Excellent article by jose On February 3, 2010

This is a great article you may also use

System.Diagnostics.Process.Start("http://www.c-sharpcorner.com");

but it depends on your needs.

Thanks!

Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.