Mar*_*cus -1 c# console-application command-line-arguments
我无法将参数传递给我的控制台应用程序。我是这样试的:
App.exe arg1
App.exe "arg1"
App.exe
Run Code Online (Sandbox Code Playgroud)
当我使用参数运行应用程序时,应用程序将退出运行,没有任何消息。
调试时没有任何内容string[] args。
我的 C# 项目是一个普通的 .net 4.5.2 命令行项目。我的操作系统是 Windows 10 x64。
示例代码:
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]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人有想法?
我进一步简化了您的代码;即我们现在来看看
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.
}
}
Run Code Online (Sandbox Code Playgroud)
以便我们以任何方式获得输出。
毫不费力地运行这个将产生
没有通过任何参数。
但是,在 Visual Studio 中,通过进入
项目 -> 属性 -> 调试
我们现在将提供一些用于调试的命令参数行。
现在运行程序将产生
计数:3 第一:-第一
对于实际使用,您可以像这样运行应用程序(例如从命令行):
app.exe -one /two three foo
Run Code Online (Sandbox Code Playgroud)
它仍然会获得所有命令行参数:
计数:4 第一个:-一个