[背景資訊]
所以我安裝了新的 Visual Studio 2022 并決定嘗試使用 .NET Core 6 來撰寫一個簡單的腳本。首先,我創建了一個新的控制臺應用程式并立即感到困惑。沒有主要方法,也沒有在檔案中寫到使用 CLI 引數(我需要傳遞兩個目標路徑引數)。我發現了一篇關于如何通過 System.Environment 類訪問引數的溢位帖子。所以我繼續前進。
[問題]
在 .NET Core 5 控制臺應用程式中,我通過 CLI 運行帶有引數的編譯可執行檔案沒有問題。但是當我發布我的代碼并通過命令列運行它時,我得到了以下輸出(見輸出)和奇怪的行“程式不能在 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);
}
[使用 Powershell & || 運行時的輸出 指令]

uj5u.com熱心網友回復:
Environment.GetCommandLineArgs()始終將行程檔案名作為第一個元素。您應該從索引 1 開始。
uj5u.com熱心網友回復:
另一種方法 - 使用編譯器生成的args引數:
入口點方法總是有一個形參,
string[] args. 執行環境創建并傳遞一個string[]包含應用程式啟動時指定的命令列引數的引數。該string[]引數永遠不會為空,但如果沒有指定命令列引數,它的長度可能為零。該args引數在頂級陳述句的范圍內,而不在它們之外的范圍內。適用常規名稱沖突/隱藏規則。
string stationIniPath = args[0];
string equipmentIniPath = args[1];
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408705.html
標籤:
上一篇:在.net中的可等待函式中等待
