user776676
user776676

Reputation: 4385

How to execute command in a C# Windows console app?

How to implement this pseudo code in a C# Windows console app?

for i=1 to 100
    rename filei newFilei

The key goal is to loop and execute any cmd command within a Windows console app.

class Program
{
    static void Main(string[] args)
    {
        string strCmdLine;
        System.Diagnostics.Process process1;
        process1 = new System.Diagnostics.Process();


        Int16 n = Convert.ToInt16(args[1]);
        int i;
        for (i = 1; i < n; i++)
        {
            strCmdLine = "/C xxxxx xxxx" + args[0] + i.ToString();
            System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
            process1.Close();
        }


    }
}

Upvotes: 0

Views: 8159

Answers (3)

Crippledsmurf
Crippledsmurf

Reputation: 4012

C# supports four different loop constructs:

  1. for
  2. foreach
  3. while
  4. do

The documentation for each of these is sufficiently detailed that I won't explain these again here.

File related operations can be performed with the File and Directory classes respectively. For example to rename a file you could use the Move method of the File class like so.

File.Move("oldName","NewName");

Because both oldName and NewName are assumed to be in the same directory, the file named oldName is renamed to NewName.

With respect to launching other applications the Process class offers the ability to launch a process and monitor it's execution. I'll leave investigating this class and it's capabilities to the reader.

The pseudo-code included in the question could be translated to the following code in C#. Please note that this sample does not include any error handling which one will always want to include in production code.

string[] sourceFileNames=new string[100];
string[] destFileNames = new string[sourceFileNames.Length];
//fill arrays with file names.
for (int i=0; i < fileNames.Length; i++)
{
File.Move(sourceFileNames[i], destFileNames[i]);
}

Upvotes: 1

CharithJ
CharithJ

Reputation: 47490

Diagnostics.Process

            System.Diagnostics.Process proc;

            cmd = @"strCmdLine = "/C xxxxx xxxx" + args[0] + i.ToString();

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

Upvotes: 3

Antony Scott
Antony Scott

Reputation: 21978

If all you're doing is renaming files you can do that by using the System.IO.File class with the Move method

http://msdn.microsoft.com/en-us/library/system.io.file.move.aspx

Upvotes: 0

Related Questions