Search
Latest topics
C# Code Snippet - Execute Shell Commands from .Net
Page 1 of 1
C# Code Snippet - Execute Shell Commands from .Net
This .Net C# code snippet executes a shell command. To use this function simply provide the file/command to execute, command line parameters (optional), string variable to store output and string variable to store errors occurred during execution.
The code creates a command process and then invokes the command that we want to execute. The result of the command and any errors occurred during execution is stored in a string variables, which can then be used for further reference. This is a great method to execute your DOS commands from .Net.
Here is a simple example showing how to use above function (ExecuteShellCommand) to execute a simple DOS dir command and show output result in a richtextbox.
This example shows how to use above method to execute DOS del command to delete all the ZIP files in c:\temp folder using .Net.
Process
Format
ProcessStartInfo
Environment
SystemDirectory
InvariantCulture
Win32Exception
Exception
Code Snippet Information:
Applies To: .Net, C#, CLI, Shell Execute from .Net, DOS, System Processes, Execute DOS Commands from .Net, Redirect Standard Output, Windows command interpreter
Programming Language : C# (C-Sharp)
The code creates a command process and then invokes the command that we want to execute. The result of the command and any errors occurred during execution is stored in a string variables, which can then be used for further reference. This is a great method to execute your DOS commands from .Net.
- Code:
/// <summary>
/// Execute a shell command
/// </summary>
/// <param name="_FileToExecute">File/Command to execute</param>
/// <param name="_CommandLine">Command line parameters to pass</param>
/// <param name="_outputMessage">returned string value after executing shell command</param>
/// <param name="_errorMessage">Error messages generated during shell execution</param>
public void ExecuteShellCommand(string _FileToExecute, string _CommandLine, ref string _outputMessage, ref string _errorMessage)
{
// Set process variable
// Provides access to local and remote processes and enables you to start and stop local system processes.
System.Diagnostics.Process _Process = null;
try
{
_Process = new System.Diagnostics.Process();
// invokes the cmd process specifying the command to be executed.
string _CMDProcess = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\cmd.exe", new object[] { Environment.SystemDirectory });
// pass executing file to cmd (Windows command interpreter) as a arguments
// /C tells cmd that we want it to execute the command that follows, and then exit.
string _Arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/C {0}", new object[] { _FileToExecute });
// pass any command line parameters for execution
if (_CommandLine != null && _CommandLine.Length > 0)
{
_Arguments += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { _CommandLine, System.Globalization.CultureInfo.InvariantCulture });
}
// Specifies a set of values used when starting a process.
System.Diagnostics.ProcessStartInfo _ProcessStartInfo = new System.Diagnostics.ProcessStartInfo(_CMDProcess, _Arguments);
// sets a value indicating not to start the process in a new window.
_ProcessStartInfo.CreateNoWindow = true;
// sets a value indicating not to use the operating system shell to start the process.
_ProcessStartInfo.UseShellExecute = false;
// sets a value that indicates the output/input/error of an application is written to the Process.
_ProcessStartInfo.RedirectStandardOutput = true;
_ProcessStartInfo.RedirectStandardInput = true;
_ProcessStartInfo.RedirectStandardError = true;
_Process.StartInfo = _ProcessStartInfo;
// Starts a process resource and associates it with a Process component.
_Process.Start();
// Instructs the Process component to wait indefinitely for the associated process to exit.
_errorMessage = _Process.StandardError.ReadToEnd();
_Process.WaitForExit();
// Instructs the Process component to wait indefinitely for the associated process to exit.
_outputMessage = _Process.StandardOutput.ReadToEnd();
_Process.WaitForExit();
}
catch (Win32Exception _Win32Exception)
{
// Error
Console.WriteLine("Win32 Exception caught in process: {0}", _Win32Exception.ToString());
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
finally
{
// close process and do cleanup
_Process.Close();
_Process.Dispose();
_Process = null;
}
}
Here is a simple example showing how to use above function (ExecuteShellCommand) to execute a simple DOS dir command and show output result in a richtextbox.
- Code:
string _Output = null;
string _Error = null;
ExecuteShellCommand("dir", "c:\\", ref _Output, ref _Error);
richTextBox1.Text = _Output;
This example shows how to use above method to execute DOS del command to delete all the ZIP files in c:\temp folder using .Net.
- Code:
/F - Force deleting of read-only files.
/Q - Quiet mode, do not ask if ok to delete on global wildcard.
string _Output = null;
string _Error = null;
ExecuteShellCommand("del", "/F /Q c:\\temp\\*.zip", ref _Output, ref _Error);
Process
Format
ProcessStartInfo
Environment
SystemDirectory
InvariantCulture
Win32Exception
Exception
Code Snippet Information:
Applies To: .Net, C#, CLI, Shell Execute from .Net, DOS, System Processes, Execute DOS Commands from .Net, Redirect Standard Output, Windows command interpreter
Programming Language : C# (C-Sharp)
Similar topics
» Lập trình shell
» Các lệnh Shell cơ bản trong Linux
» cơ bản trong command shell của windows XP
» Http code
» Code thêm xóa sửa tìm kiếm trong c#
» Các lệnh Shell cơ bản trong Linux
» cơ bản trong command shell của windows XP
» Http code
» Code thêm xóa sửa tìm kiếm trong c#
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
Thu Aug 23, 2012 5:38 am by Admin
» Tuyệt kỹ cua giai
Thu Aug 23, 2012 5:36 am by Admin
» NETCAT.........
Mon Aug 13, 2012 6:35 am by Admin
» Bảo mật CSDL bằng phương pháp mã hóa.
Tue Apr 17, 2012 10:04 pm by Admin
» Hàm mã hóa MD5 bằng JavaScript
Tue Apr 17, 2012 10:03 pm by Admin
» Giá của món quà
Fri Apr 13, 2012 6:01 am by Admin
» Sẽ chỉ yêu ai?
Fri Apr 13, 2012 6:01 am by Admin
» Cách đọc bảng chữ cái!
Thu Apr 12, 2012 10:37 pm by Admin
» Gắn trojan, keylog, virus vào website, forum
Tue Apr 10, 2012 1:14 am by Admin