-6

I need to write a windows form app, WPF, or console application that should run this from a command prompt:

@echo off
echo test
or
del c:\b.txt

The c# code needs to be on a button but It's not important now. I tried this:

    using System;
    using System.Diagnostics;
    using System.ComponentModel;

    private void button1_Click(object sender, EventArgs e)
    {
        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        //process.StartInfo.WorkingDirectory = "c:\temp";
        //process.StartInfo.Arguments = "somefile.txt";
        Process.Start("cmd", "/dir");

    }

but i can't put my CMD code in this ^ code.

1 Answers1

0

I believe what you want is this:

Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
// add /C for command, a space, then command
psi.Arguments = "/C dir";
p.StartInfo = psi;
p.Start();

The above code allows you to execute the commands directly in the cmd.exe instance. For example, to launch command prompt and see a directory, you assign the Arguments property of the ProcessStartInfo instance to "/C dir", which means execute the command called dir.

Another approach you could use is seen here:

// put your DOS commands in a batch file
ProcessStartInfo startInfo = new ProcessStartInfo("action.bat");
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = "C:\\dir"; 
Process.Start(startInfo);

Put the above code in your click event.

Create a batch file with your commands using instructions found at http://www.ehow.com/how_6534808_create-batch-files.html

In my code example, if you name the batch file 'action.bat' and place it in th c:dir folder, everything will work the way you want.

Cheers :)

Michael Palermo
  • 296
  • 2
  • 9