如果命令行参数不正确,则向控制台窗口输出消息

时间:2013-11-15 16:11:17

标签: c# winforms

当我的.exe被错误的参数调用时,有人可以帮我输出一个消息到控制台吗?

昨天,一些非常善良的人帮我解决了如何在没有用户界面的情况下调用我的应用程序

这是线程

command line to make winforms run without UI

所以,我告诉我的应用程序回复“/ silent archive = true transcode = true”并在没有UI的情况下运行。太好了!

如果命令输出不正确,是否可以将命令输出到命令窗口?

如“参数必须像这样指定:/ silent archive = true transcode = true”

我试过这个,但在dos窗口中没有显示..

static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            if (args[0] == "/silent")
            {
                bool archive = false;
                bool transcode = false;

                try
                {
                    if (args[1] == "transcode=true") { transcode = true; };
                    if (args[2] == "archive=true") { archive = true; };
                    Citrix_API_Tool.Engine.DownloadFiles(transcode, archive);
                }
                catch
                {
                    Console.Write ("Hello");
                    Console.ReadLine();
                    return;
                }
            }
        }
        else

1 个答案:

答案 0 :(得分:0)

internal sealed class Program
{
  [DllImport("kernel32.dll")]
  private static extern bool AttachConsole(int dwProcessId);

  private const int ATTACH_PARENT_PROCESS = -1;
  [STAThread]
  private static void Main(string[] args)
  {
    if(false)//This would be the run-silent check.
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new MainForm());
    }
    try
    {
      throw new Exception("Always throw, as this tests exception handling.");
    }
    catch(Exception e)
    {
      if(AttachConsole(ATTACH_PARENT_PROCESS))
      {
        //Note, we write to Console.Error, not Console.Out
        //Partly because that's what error is for.
        //Mainly so if our output were being redirected into a file,
        //We'd write to console instead of there.
        //Likewise, if error is redirected to some logger or something
        //That's where we should write.
        Console.Error.WriteLine();//Write blank line because of issue described below
        Console.Error.WriteLine(e.Message);
        Console.Error.WriteLine();//Write blank line because of issue described below
      }
      else
      {
        //Failed to attach - not opened from console, or console closed.
        //do something else.
      }
    }
  }      
}

问题是控制台已经返回以从用户那里获取输入。因此,如果你想拥有它,你真的想尽可能快地检查你的异常,因此最好快速验证检查而不是可能发生的异常。