代码之家  ›  专栏  ›  技术社区  ›  Ilya Volodin

C发布版本中的命令行参数问题

  •  0
  • Ilya Volodin  · 技术社区  · 16 年前

    我有一个我自己解决不了的简单问题。我有一个WinForm应用程序,修改了主方法以接受如下命令行参数:

        [STAThread]
        static void Main(String[] args)
        {
            int argCount = args.Length;
        }
    

    当使用以下执行行在调试模式下编译时,此代码工作正常,argcount等于2:program.exe-file test.txt。 但是,当我以发布模式编译程序时,argcount现在是1,具有相同的命令行参数。唯一的参数包含“-file test.txt”。更重要的是,只有我从obj/release文件夹运行编译的可执行文件,而不是从bin/release运行编译的可执行文件时才会发生这种情况。不幸的是,安装项目从obj/release获取可执行文件,所以我无法更改。 这是一个已知的问题,有没有解决这个问题的方法?

    4 回复  |  直到 16 年前
        1
  •  1
  •   Richard    16 年前

    命令行处理应该是相同的,因此正在进行其他操作。当我尝试这个的时候:

    class Program {
        [STAThread]
        static void Main(String[] args) {
            Console.WriteLine("Have {0} arguments", args.Length);
            for (int i = 0; i < args.Length; ++i) {
                Console.WriteLine("{0}: {1}", i, args[i]);
            }
        }
    }
    

    然后从不同的位置得到100%一致的结果,获得参数“合并”的唯一方法是在命令行中用引号括起来(特别是在命令行中允许您有包含空格的参数,请参见下面的最后一个示例):

    PS C:\...\bin\Debug> .\ConsoleApplication1.exe one two three
    Have 3 arguments
    0: one
    1: two
    2: three
    PS C:\...\bin\Debug> pushd ..\release
    PS C:\...\bin\Release> .\ConsoleApplication1.exe one two three
    Have 3 arguments
    0: one
    1: two
    2: three
    PS C:\...\bin\Release> pushd ..\..\obj\debug
    PS C:\...\obj\Debug> .\ConsoleApplication1.exe one two three
    Have 3 arguments
    0: one
    1: two
    2: three
    PS C:\...\obj\Debug> pushd ..\release
    PS C:\...\obj\Release> .\ConsoleApplication1.exe one two three
    Have 3 arguments
    0: one
    1: two
    2: three
    PS C:\...\obj\Release> .\ConsoleApplication1.exe -file test.txt
    Have 2 arguments
    0: -file
    1: test.txt
    PS C:\...\obj\Release> .\ConsoleApplication1.exe "-file test.txt"
    Have 1 arguments
    0: -file test.txt
    

    附加的 虽然从命令提示符启动可以很容易地看到正在传递的内容,但当另一个应用程序启动您的应用程序时,可能很难进行检查。但是工具喜欢 Process Explorer 将显示用于启动程序的命令行(双击进程并查看图像选项卡)。

        2
  •  1
  •   pero    16 年前

    这在bin/debug、bin/release、obj/debug和obj/release中适用:

    static class Program {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main(string[] args) {
        FormMain.Args = args;
    
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FormMain());
      }
    }
    
      public partial class FormMain: Form {
        public static string[] Args;
    
        public FormMain() {
          InitializeComponent();
        }
    
        private void FormMain_Shown(object sender, EventArgs e) {
          foreach (string s in Args) {
            MessageBox.Show(s);
          }
        }
      }
    
        3
  •  0
  •   Greg D    16 年前
        4
  •  0
  •   cjk    16 年前

    您的问题(正如Richard在代码中指出的那样)是,运行发布版本时的参数都包含在一组引号中。去掉引号,它就可以工作了。