简体   繁体   中英

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

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? :SI 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>

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

请参阅下面的args,您可以使用它来读取运行exe文件时传递的所有值。

static void Main(string[] args) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM