Reputation: 690
I can't pass arguments to my console app. I tried it like this:
App.exe arg1
App.exe "arg1"
App.exe
When I run the app with arguments, the app quits running without any messages.
When debugging there is nothing in string[] args
.
My C# project is a plain .net 4.5.2 command line project. My OS is Windows 10 x64.
Sample Code:
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
namespace Setup
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
using (PowerShell psInstance = PowerShell.Create())
{
string cmd = "Set-ExecutionPolicy RemoteSigned -Force; " +
"echo \"Set-ExecutionPolicy RemoteSigned -Force\"; echo \"\"; " +
"Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force; ";
psInstance.AddScript(cmd);
Collection<PSObject> PSOutput = psInstance.Invoke();
Console.WriteLine(psInstance.Streams.Error[0].ErrorDetails.Message);
foreach (var item in PSOutput)
{
if (item != null)
{
Console.WriteLine(item.BaseObject.ToString());
}
}
Console.ReadLine();
}
}
else
{
// Will not work
Console.WriteLine(args[0]);
}
}
}
}
Does anyone have an idea?
Upvotes: 0
Views: 23338
Reputation: 5115
I simplified your code a bit further; namely we will now look at
public class Program
{
public static void Main(string[] args)
{
int numberOfArguments = args.Length;
if (numberOfArguments > 0)
{
Console.WriteLine($"Count: {numberOfArguments} First: {args[0]}");
}
else
{
Console.WriteLine("No arguments were passed.");
}
Console.ReadLine(); // Keep the console open.
}
}
so that we get an output either way.
Running this without any further ado will yield
No arguments were passed.
However, in Visual Studio, by going into
Project -> Properties -> Debug
we will now provide some command argument lines for debugging.
Running the program now will yield
Count: 3 First: -first
For real world use, you can then run the app (e.g. from the command line) like this:
app.exe -one /two three foo
and it will still get all of the command line arguments:
Count: 4 First: -one
Upvotes: 8
Reputation: 135
It will be helpful if you can share the code.
Sample program to print zero position argument will be :
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(args[0]);
}
}
}
You can call it from commandline
ConsoleApplication1.exe argument1
Upvotes: 0