![](/img/trans.png)
[英].Net Core Console App Logging feature - why does my Console.WriteLine appear outside start and end logging?
[英]Why does my .NET Core 6 console app not want to run in CLI?
[背景信息]
所以我安装了新的 Visual Studio 2022 并决定尝试使用 .NET Core 6 来编写一个简单的脚本。 首先,我创建了一个新的控制台应用程序并立即感到困惑。 没有主要方法,也没有在文档中写到使用 CLI arguments(我需要传递两个目标路径参数)。 我发现了一篇关于如何通过 System.Environment class 访问 arguments 的溢出帖子。 所以我继续前进。
[问题]
在 .NET Core 5 控制台应用程序中,我通过 CLI 使用 arguments 运行编译的可执行文件没有问题。 但是当我发布我的代码并通过命令行运行它时,我得到了以下 output (见输出)和奇怪的行“程序无法在 DOS 模式下运行”。 有趣的是,它仍然会读取一个 ini 文件,但是当我运行 powershell 时,它会读取另一个 ini。 这对我来说是非常奇怪的行为。 我应该降级回 .NET Core 5 还是尝试了解发生了什么? 这是我正在阅读INI的事实吗? (不幸的是,我别无选择,因为它是一个遗留项目)。 任何帮助表示赞赏。
[代码]
using System.IO;
//get command line arguments
try
{
string stationIniPath = Environment.GetCommandLineArgs()[0];
string equipmentIniPath = Environment.GetCommandLineArgs()[1];
Console.WriteLine("- Reading INI data -");
if(stationIniPath != null && equipmentIniPath != null){
string[] stationINI = System.IO.File.ReadAllLines(stationIniPath);
string[] equipmentINI = System.IO.File.ReadAllLines(equipmentIniPath);
foreach(string station in stationINI)
{
Console.WriteLine(station);
}
foreach(string equipment in equipmentINI)
{
Console.WriteLine(equipment);
}
}
else
{
throw new Exception("Need to specify command line arguments");
}
}
catch (Exception e)
{
Console.WriteLine("You must specify arguments [0] Station INI Path and [1] Equipment INI path : " + e.Message);
}
Environment.GetCommandLineArgs()
始终将进程文件名作为第一个元素。 您应该从索引 1 开始。
另一种方法 - 使用编译器生成的args
参数:
入口点方法总是有一个形式参数
string[] args
。 执行环境创建并传递一个string[]
参数,其中包含在启动应用程序时指定的命令行 arguments。string[]
参数永远不会是 null,但如果没有指定命令行 arguments,它的长度可能为零。args
参数在顶级语句中的 scope 中,而不在它们之外的 scope 中。 适用常规名称冲突/隐藏规则。
string stationIniPath = args[0];
string equipmentIniPath = args[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.