How to set C# application to accept Command Line Parameters? [duplicate] - c#

This question already has answers here:
Best way to parse command line arguments in C#? [closed]
(20 answers)
Closed 5 years ago.
I have created a C# command line application that creates a few reports automatically for my client. However, even though they use 95% of the same code I would like to split them in to different processes. I am using Windows task scheduler to run them. How do I set up the C# application to accept Command line parameters upon runtime?
I cannot find any explanation of this on the internet.

All command line parameters are passed to your application through string[] args parameter. The code below shows an example:
using System.Linq;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("/REPORT1"))
{
/* Do something */
}
else if (args.Contains("/REPORT2"))
{
/* Do something */
}
}
}
}
Then, in command prompt just use:
C:\MyApp\MyApp.exe /REPORT1

MSDN
The below snippet will print the number of parameters passed from the command line... string[] args contains the parameter values...
class TestClass
{
static void Main(string[] args)
{
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}

Related

C# passing array to array but still getting "cannot convert from 'string[]' to 'string'” error

(using VS Community 2019 v16.10.4 on Win 10 Pro 202H)
I'm working on a C# console/winforms desktop app which monitors some local drive properties and displays a status message. Status message display is executed via Task Scheduler (the task is programmatically defined and registered). The UI is executed from the console app using the Process method. My intention is to pass an argument from Scheduler to the console app, perform some conditional logic and then pass the result to the UI entry (Program.cs) for further processing.
I’m testing passing an argument from the console app to the UI entry point and I’m getting a “Argument 1: cannot convert from 'string[]' to 'string'” error.
Code is:
class Program_Console
{
public static void Main(string[] tsArgs)
{
// based on MSDN example
tsArgs = new string[] { "Test Pass0", "TP1", "TP2" };
Process p = new Process();
try
{
p.StartInfo.FileName = BURS_Dir;
p.Start(tsArgs); // error here
}
public class Program_UI
{
[STAThread]
public void Main(string[] tsArgs)
{
Isn’t "tsArgs" consistently an array?
EDIT:
For clarity I’m using .NET Framework 4.7.2. The problem was not with consistency of what I am passing but in the Process.Start(String, IEnumerable String) overload. I believed “IEnumerable String” included string[ ]; it obviously does not since I was able to pass a plain string (not a string variable -- that also failed – just a hardcoded string).
In case it’s useful to somebody, my work-around is saving the arguments to a SQLite table in the console app and loading them into a List in the UI app. I’m sure a more proficient programmer could do it more efficiently.
Start doesn' have a costractor with string array. if you look at msdn document youi will see that you can use something the closest to your example
public static Start (string fileName, IEnumerable<string> arguments);
so you can try
p.Start( filename,tsArgs );
and replace filename with yours
The only Start() method taking arguments as an array also needs the filename: Start(). You can't set the Filename via StartInfo and then omit that parameter in the method call.
The following should work for you:
p.Start(BURS_Dir, tsArgs);
In .Net 5.0+, and .Net Core and Standard 2.1+, you can use a ProcessStartInfo for multiple command-line arguments
tsArgs = new string[] { "Test Pass0", "TP1", "TP2" };
Process p = new Process();
try
{
p.StartInfo.FileName = BURS_Dir;
foreach (var arg in tsArgs)
p.StartInfo.ArgumentList.Add(arg);
p.Start();
}
catch
{ //
}
Alternatively, just add them directly
Process p = new Process
{
StartInfo =
{
FileName = BURS_Dir,
ArgumentList = { "Test Pass0", "TP1", "TP2" },
}
};
try
{
p.Start();
}
catch
{ //
}

Command Line Parser library giving 'System.Type' error in C#

I'm writing a Console App (.NET Framework) in C#. I want to use arguments from the command line, and I'm trying to use the Command Line Parser library to help me do this.
This is the package on Nuget - https://www.nuget.org/packages/CommandLineParser/
I found out about it from this StackOverflow question - Best way to parse command line arguments in C#?
MWE
using System;
using CommandLine;
namespace CLPtest
{
class Program
{
class SomeOptions
{
[Option('n', "name")]
public string Name { get; set; }
}
static void Main(string[] args)
{
var options = new SomeOptions();
CommandLine.Parser.Default.ParseArguments(args, options);
}
}
}
When I try create a minimal working example, I get an error for options on this line:
CommandLine.Parser.Default.ParseArguments(args, options);
The error is Argument 2: cannot convert from 'CLPtest.Program.SomeOptions' to 'System.Type'
I'm really confused as I have seen this same example code on at least 3 tutorials for how to use this library. (see for example - Parsing Command Line Arguments with Command Line Parser Library)
(This answer is being written at the time of v2.7 of this library)
From looking at their repository's README, it appears as if this is part of the API change that is mentioned earlier in the README. It looks as though the arguments are now handled differently since the example code you reference. So, now you should do something like this inside of Main:
...
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<SomeOptions>(args);
}
...
To actually do something with those options you can use WithParsed which takes in the options that are defined in your SomeOptions class.
...
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(option =>
{
// Do something with your parsed arguments in here...
Console.WriteLine(option.Name); // This is the property from your SomeOptions class.
});
}
...
The C# Example further down the README shows that you can pass in a method into WithParsed to handle your options instead of doing everything within Main.

Execute the C# console exe with command line arguments from VB Project

How to call an exe written in C# which accepts command line arguments from VB.NET application.
For Example, Let's assume the C# exe name is "SendEmail.exe" and its 4 arguments are From ,TO ,Subject and Message and If I have placed the exe in the C drive. This is how I call from the command prompt
C:\SendEmail from#email.com,to#email.com,test subject, "Email Message " & vbTab & vbTab & "After two tabs" & vbCrLf & "I am next line"
I would like to call this "SendEmail" exe from the VB.NET application and pass the command line arguments from VB (arguments will be using vb Syntax like vbCrLf, VBTab etc). This problem may look silly but I am trying to divide the complex problem into series of smaller issues and conquer it.
Because your question has the C# tag, I'll suggest a C# solution you can re-spin in your preferred language.
/// <summary>
/// This will run the EXE for the user. If arguments are passed, then arguments will be used.
/// </summary>
/// <param name="incomingShortcutItem"></param>
/// <param name="xtraArguments"></param>
public static void RunEXE(string incomingExePath, List<string> xtraArguments = null)
{
if (File.Exists(incomingExePath))
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
System.Diagnostics.Process proc = new System.Diagnostics.Process();
if (xtraArguments != null)
{
info.Arguments = " " + string.Join(" ", xtraArguments);
}
info.WorkingDirectory = System.IO.Path.GetDirectoryName(incomingExePath);
info.FileName = incomingExePath;
proc.StartInfo = info;
proc.Start();
}
else
{
//do your else thing here
}
}
You might not need to call it via the console. If it's done in C# and marked public instead of internal or private, or if it relies on a public type, you may be able to add it as a reference in your VB.Net solution and call the method you want directly.
This is so much cleaner and better because you don't have to worry about things like escaping spaces or quotes in your subject or body arguments.
If you have control over the SendMail program, you make it accessible with a few simple changes. By default, a C# Console project gives you something like this:
using ....
// several using blocks at the top
// class name
class Program
{
//static Main() method
static void Main(string[] args)
{
//...
}
}
You can make it available to use from VB.Net like this:
using ....
// several using blocks at the top
//Make sure an explicit namespace is declared
namespace Foo
{
// make the class public
public class Program
{
//make the method public
static void Main(string[] args)
{
//...
}
}
}
That's it. Again, just add the reference in your project, Import it at the top of your VB.Net file, and you can call the Main() method directly, without going through the console. It doesn't matter that's it an .exe instead of a .dll. In the .Net world, they're all just assemblies you can use.

Have PowerShell script use C# code, then pass arguments to Main method

I found a technet blog article the said it was possible to have PowerShell use C# code.
Article: Using CSharp (C#) code in Powershell scripts
I found the format I need to get the C# code to work in PowerShell, but if it don't pass the Main method an argument ([namespace.class]::Main(foo)) the script throws an error.
Is there a way I can pass a string of "on" or "off" to the main method, then depending on which string is passed run an if statement? If this is possible can you provide examples and/or links?
Below is the way I'm currently trying to structure my code.
$Assem = #( //assemblies go here)
$source = #"
using ...;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args )
{
if(args == on)
{//post foo }
if(arge == off)
{ //post bar }
}
"#
Add-Type -TypeDefinition $Source -ReferencedAssumblies $Assem
[AlertsOnOff.onOff]::Main(off)
#PowerShell script code goes here.
[AlertsOnOff.onOff]::Main(on)
Well to start, if you are going to compile and run C# code, you need to write valid C# code. On the PowerShell side, if you invoke Main from PowerShell, you need to pass it an argument. PowerShell will automatically put a single argument into an array for you, but it won't insert an argument if you don't have one. That said, its not clear why this is in a Main method. It's not an executable. It could very well just have two static methods, TurnOn and TurnOff. The code below compiles and runs, modify as you see fit:
$source = #"
using System;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args)
{
if(args[0] == `"on`")
{
Console.WriteLine(`"foo`");
}
if(args[0] == `"off`")
{
Console.WriteLine(`"bar`");
}
}
}
}
"#
Add-Type -TypeDefinition $Source
[AlertsOnOff.onOff]::Main("off")
# Other code here
[AlertsOnOff.onOff]::Main("on")

How to write a program in C# that can take arguments

I've seen alot of command-line programs that take arguments, like ping google.com -t. How can I make a program like ping? I would like my program to take a number as an argument and then further use this number:
For example:
geturi -n 1188
Just write a generic, console application.
The main method looks like the following snippet:
class Program
{
static void Main(string[] args)
{
}
}
Your arguments are included in the args array.
With a normal Console Application, in static void Main(string[] args), simply use the args. If you want to read the first argument as a number, then you simply use:
static void Main(string[] args)
{
if (args.Length > 1)
{
int arg;
if (int.TryParse(args[0], out arg))
// use arg
else // show an error message (the input was not a number)
}
else // show an error message (there was no input)
}

Categories