开发者

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

开发者 https://www.devze.com 2023-02-26 03:10 出处:网络
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.

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开发者_StackOverflow社区 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


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) {
0

精彩评论

暂无评论...
验证码 换一张
取 消