Execute command of OS

  • Thread starter Thread starter alberto
  • Start date Start date
A

alberto

How can I execute a command of the operating system like "cls" from a C#
code?
Thank you
 
Use the Process class under System.Diagnostics namespace the help files
have some examples of how to use it.
 
Hi,


alberto said:
How can I execute a command of the operating system like "cls" from a C#
code?

You execute an external process using the Process class.

The example you use DO NOT WORK though, as cls is an internal command of the
command prompt, it's not an executable.
The same goes with dir , mkdir, etc.
 
alberto said:
How can I execute a command of the operating system like "cls" from a C#
code?
Thank you
To execute normal program files (.exe, .com, etc.) you just use
System.Diagnostics.Process.Start("test.exe") (look in the Process class
there, more ways to do it than just .Start(programname)).

However, CLS, DIR, etc. are internal commands for the command shell and
to execute them you need to do it through the command shell executable.

For NT-based operating systems, do:

CMD.EXE /C DIR

for Win9x, do:

COMMAND.EXE /C DIR

You can probably find the right name of the program to execute by
looking in the environment variables, look for the COMSPEC variable.

Example:

System.Diagnostics.Process.Start(Environment.GetEnvironmentVariable("COMSPEC"),
@"/C DIR C:\ >C:\test.txt");
System.Diagnostics.Process.Start(@"NOTEPAD.EXE", @"C:\TEST.TXT");
 
Back
Top