How do I use command line arguments in my C# console app?

核能气质少年 提交于 2019-12-28 17:55:49

问题


I am writing a url shortener app and I would like to also create a console app with C# to push the URLs to a WCF service which I have also created.

WCF app will shorten the url on this URI;

http://example.com/shorten/http://exaple.com

so what I want is just that.

My console exe file will be sitting inside c:\dev folder and on Windows command line, I would like to do this;

c:\dev>myapp -throw http://example.com

with this method I would like to talk to that service. there is no problem on talking part. But the problem is how can I supply this -throw thing on the command line and get a response and put that response on the command line and supply a method to copy that to the clipboard. Am I asking too much here? :S I don't know.

Could you direct me somewhere that I can find information on that or could u please give me an example code of this?

Thanks.

EDIT : I have tried the following code;

    class Program {

    static void Main(string[] args) {

        if (args[0] == "-throw") {

            System.Windows.Forms.Clipboard.SetDataObject(args[1]);
            Console.WriteLine(args[1] + " has been added to clipboard !");
            Console.ReadLine();

        }

    }
}

and I received the following error;

C:\Apps\ArgsTry\ArgsTry\bin\Debug>ArgsTry -throw man

Unhandled Exception: System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensur e that your Main function has STAThreadAttribute marked on it. at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, In t32 retryTimes, Int32 retryDelay) at System.Windows.Forms.Clipboard.SetDataObject(Object data) at ArgsTry.Program.Main(String[] args) in c:\apps\ArgsTry\ArgsTry\Program.cs: line 14

C:\Apps\ArgsTry\ArgsTry\bin\Debug>


回答1:


Passing arguments to a console application is easy:

using System;

public class CommandLine
{
   public static void Main(string[] args)
   {
       for(int i = 0; i < args.Length; i++)
       {
           if( args[i] == "-throw" )
           {
               // call http client args[i+1] for URL
           }
       }
   }
}

As for the clipboard, see:

http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.aspx




回答2:


See the args below, you can use it to read all the values passed when you run your exe file.

static void Main(string[] args) {


来源:https://stackoverflow.com/questions/5700631/how-do-i-use-command-line-arguments-in-my-c-sharp-console-app

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