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

前提是你 提交于 2020-02-05 04:52:27

问题


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();
        }


    }
}

回答1:


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();



回答2:


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]);
}



回答3:


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



来源:https://stackoverflow.com/questions/6798547/how-to-execute-command-in-a-c-sharp-windows-console-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!