在C#中解析命令行参数 [英] Parsing Command Line Arguments in C#

查看:71
本文介绍了在C#中解析命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,他编写了一个简单的程序,该程序在命令行中读取,然后使用Process.Start with CMD.EXE执行自变量.发生了一些可选替换,但这不是我的问题.我的程序叫做SysRun:

I'm new to C# annd writing a simple program that reads in a command line and then executes the arguments using Process.Start with CMD.EXE. There is some OPTIONAL substitution happening but that's not my problem. My program is called SysRun:

 静态整数Main(string [] args)
    {
   字符串strCmdText ="/C";
    ...
    //处理参数以构建[添加到] strCmdText
    for(int x = 0; x< args.Length; x ++)
       {
      如果(x> 0)
          {
          strCmdText + =" "
          }
       strCmdText + = args [x];
       }
    ...
 进程P = Process.Start("CMD.exe",strCmdText);
    ...
  }

  static int Main(string[] args)
    {
    string strCmdText = "/C ";
    ...
    // Process arguments to build [add to] strCmdText
    for (int x = 0; x < args.Length; x++)
        {
        if (x > 0)
           {
           strCmdText += " ";
           }
        strCmdText += args[x];
        }
     ...
  Process P = Process.Start("CMD.exe", strCmdText);
     ...
  }

例如,我从一个批处理文件执行它:

So for example, I execute it from a batch file:

  SysRun xcopy from.txt to.txt

  SysRun xcopy from.txt to.txt

这很好用,就像我介绍>时我测试过的所有其他东西一样,例如:

This works just fine just as everything else I have tested EXCEPT when I introduce a >, example:

  SysRun目录dir.txt
 
这是行不通的.我可以在命令行上看到:

  SysRun dir > dir.txt
 
This doesn't work. I can see on the command line:

  SysRun目录1> dir.txt

  SysRun dir  1>dir.txt

,并且在控制台上显示dir输出,而不是重定向到dir.txt.有什么我想念的吗?进行某些设置或切换? C#处理命令行参数是否与C不同?我一直在到处寻找任何相关的东西 对此,并提出空了.谢谢.

and the dir output shows on the console instead of being redirected to dir.txt. Is there something I'm missing? Some setting or switch somewhere? Does C# process command line arguments differently than C? I've been looking everywhere for anything related to this and have come up empty. Thx.

推荐答案

尝试一下:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.Arguments = "/C " + string.Join( " ", args );
psi.UseShellExecute = false;
Process p = Process.Start( psi );
p.WaitForExit();


这篇关于在C#中解析命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆