tags:

views:

353

answers:

6

how to translate system("") to C# without calling cmd.exe? edit: i need to throw something like "dir"

+3  A: 

Not sure if I understand your question. Are you looking for Process.Start ?

nc3b
+6  A: 

If I correctly understood your question, you're looking for Process.Start.

See this example (from the docs):

// Opens urls and .html documents using Internet Explorer.
void OpenWithArguments()
{
    // url's are not considered documents. They can only be opened
    // by passing them as arguments.
    Process.Start("IExplore.exe", "www.northwindtraders.com");

    // Start a Web page using a browser associated with .html and .asp files.
    Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
    Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
 }

Edit

As you said you needed something like the "dir" command, I would suggest you to take a look at DirectoryInfo. You can use it to create your own directory listing. For example (also from the docs):

// Create a DirectoryInfo of the directory of the files to enumerate.
DirectoryInfo DirInfo = new DirectoryInfo(@"\\archives1\library");

DateTime StartOf2009 = new DateTime(2009, 01, 01);

// LINQ query for all files created before 2009.
var files = from f in DirInfo.EnumerateFiles()
           where DirInfo.CreationTimeUtc < StartOf2009
           select f;

// Show results.
foreach (var f in files)
{
    Console.WriteLine("{0}", f.Name);
}
Fernando
And you should avoid system() in first place in your original C application.
Matteo Italia
dir was just an example i want to simulate cmd.exe
Whatever were you trying to achieve with system, there's almost certainly a cleaner way to do that directly from C/C#. *system* is a function to avoid.
Matteo Italia
+1  A: 

As other folks noted, it's Process.Start. Example:

using System.Diagnostics;

// ...

Process.Start(@"C:\myapp\foo.exe");
John Feminella
+1  A: 

Do you actually want the equivalent? You may not depending on what exactly you're trying to do.

For example calling copy from the command line has a C# equivalent itself, File.Copy, for dir there's a whole Directory class for getting info (these are a quick 2 out of thousands of examples). Depending on what you're after, C# most likely has a library/function for the specific command you're trying to run, usually a more robust method as well, instead of a global handler.

If the global "invoke this" is what you're after, then as the other answers suggest, using the System.Diagnostics.Process class is your best bet.

Nick Craver
+2  A: 
I need to throw something like "dir"

If you need to run DIR, then you need to call cmd.exe as dir is internal to cmd.exe

Joshua
A: 

If you want to execute a command-line (cmd.exe) command, such as "dir" or "time" or "mkdir", pass the command as an argument to cmd.exe with the flag /C.

For example,

cmd.exe /C dir

or

cmd.exe /C mkdir "New Dir"
Andreas Rejbrand