使用 .NET Core CLI 建立 .NET Core 通用工具Create a .NET Core Global Tool using the .NET Core CLI

本文會教導您如何建立及封裝 .NET Core 通用工具。This article teaches you how to create and package a .NET Core Global Tool. .NET Core CLI 可讓您建立作為通用工具的主控台應用程式,其他人也可以輕鬆地安裝及執行該工具。The .NET Core CLI allows you to create a console application as a Global Tool, which others can easily install and run. .NET Core 通用工具是從 .NET Core CLI 安裝的 NuGet 套件。.NET Core Global Tools are NuGet packages that are installed from the .NET Core CLI. 如需通用工具的詳細資訊,請參閱 .NET Core 通用工具概觀For more information about Global Tools, see .NET Core Global Tools overview.

本文適用於:✓ .NET Core 2.1 SDKThis article applies to: ✓ .NET Core 2.1 SDK

建立專案Create a project

本文使用 .NET Core CLI 來建立和管理專案。This article uses the .NET Core CLI to create and manage a project.

我們的範例工具是會產生 ASCII Bot 並列印訊息的主控台應用程式。Our example tool will be a console application that generates an ASCII bot and prints a message. 首先,建立新的 .NET Core 主控台應用程式。First, create a new .NET Core Console Application.

dotnet new console -o botsay

瀏覽至先前命令所建立的 botsay 目錄。Navigate to the botsay directory created by the previous command.

新增程式碼Add the code

使用您慣用的文字編輯器 (例如 vimVisual Studio Code),開啟 Program.cs 檔案。Open the Program.cs file with your favorite text editor, such as vim or Visual Studio Code.

將下列 using 指示詞新增至檔案頂端,這有助於縮短用來顯示應用程式版本資訊的程式碼。Add the following using directive to the top of the file, this helps shorten the code to display the version information of the application.

using System.Reflection;

接下來,向下移動至 Main 方法。Next, move down to the Main method. 使用下列程式碼來取代方法,以處理應用程式的命令列引數。Replace the method with the following code to process the command-line arguments for your application. 如果未傳遞任何引數,則會顯示簡短的說明訊息。If no arguments were passed, a short help message is displayed. 否則,所有引數都會轉換成字串並且以 Bot 列印。Otherwise, all of those arguments are transformed into a string and printed with the bot.

static void Main(string[] args)
{
    if (args.Length == 0)
    {
        var versionString = Assembly.GetEntryAssembly()
                                .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
                                .InformationalVersion
                                .ToString();

        Console.WriteLine($"botsay v{versionString}");
        Console.WriteLine("-------------");
        Console.WriteLine("\nUsage:");
        Console.WriteLine("  botsay <message>");
        return;
    }

    ShowBot(string.Join(' ', args));
}

建立 BotCreate the bot

接下來,新增名為 ShowBot 的新方法來採用字串參數。Next, add a new method named ShowBot that takes a string parameter. 這個方法會列印出訊息和 ASCII Bot。This method prints out the message and the ASCII bot. ASCII Bot 程式碼取自 dotnetbot 範例。The ASCII bot code was taken from the dotnetbot sample.

static void ShowBot(string message)
{
    string bot = $"\n        {message}";
    bot += @"
    __________________
                      \
                       \
                          ....
                          ....'
                           ....
                        ..........
                    .............'..'..
                 ................'..'.....
               .......'..........'..'..'....
              ........'..........'..'..'.....
             .'....'..'..........'..'.......'.
             .'..................'...   ......
             .  ......'.........         .....
             .    _            __        ......
            ..    #            ##        ......
           ....       .                 .......
           ......  .......          ............
            ................  ......................
            ........................'................
           ......................'..'......    .......
        .........................'..'.....       .......
     ........    ..'.............'..'....      ..........
   ..'..'...      ...............'.......      ..........
  ...'......     ...... ..........  ......         .......
 ...........   .......              ........        ......
.......        '...'.'.              '.'.'.'         ....
.......       .....'..               ..'.....
   ..       ..........               ..'........
          ............               ..............
         .............               '..............
        ...........'..              .'.'............
       ...............              .'.'.............
      .............'..               ..'..'...........
      ...............                 .'..............
       .........                        ..............
        .....
";
    Console.WriteLine(bot);
}

測試工具Test the tool

執行專案,並查看輸出結果。Run the project and see the output. 請嘗試這些命令列變化,以查看不同的結果:Try these variations of the command-line to see different results:

dotnet run
dotnet run -- "Hello from the bot"
dotnet run -- hello from the bot

-- 分隔符號之後的所有引數會傳遞至您的應用程式。All arguments after the -- delimiter are passed to your application.

安裝通用工具Setup the global tool

在您可以將應用程式封裝及散佈為通用工具之前,您應該修改專案檔案。Before you can pack and distribute the application as a Global Tool, you need to modify the project file. 開啟 botsay.csproj 檔案,然後將三個新 XML 節點新增至 <Project><PropertyGroup> 節點:Open the botsay.csproj file and add three new XML nodes to the <Project><PropertyGroup> node:

  • <PackAsTool>
    [必要] 表示會封裝應用程式以安裝為通用工具。[REQUIRED] Indicates that the application will be packaged for install as a Global Tool.

  • <ToolCommandName>
    [選用] 工具的替代名稱,否則工具的命令名稱會跟隨著專案檔案命名。[OPTIONAL] An alternative name for the tool, otherwise the command name for the tool will be named after the project file. 您在套件中可以有多個工具,選擇唯一且易記的名稱,有助於與相同套件中的其他工具區分。You can have multiple tools in a package, choosing a unique and friendly name helps differentiate from other tools in the same package.

  • <PackageOutputPath>
    [選用] 在其中產生 NuGet 套件的位置。[OPTIONAL] Where the NuGet package will be produced. NuGet 套件是 .NET Core CLI 通用工具用來安裝工具的套件。The NuGet package is what the .NET Core CLI Global Tools uses to install your tool.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>

    <PackAsTool>true</PackAsTool>
    <ToolCommandName>botsay</ToolCommandName>
    <PackageOutputPath>./nupkg</PackageOutputPath>

  </PropertyGroup>

</Project>

即使 <PackageOutputPath> 是選擇性的,請在此範例中使用它。Even though <PackageOutputPath> is optional, use it in this example. 請確定您已設定:<PackageOutputPath>./nupkg</PackageOutputPath>Make sure you set it: <PackageOutputPath>./nupkg</PackageOutputPath>.

接下來,為您的應用程式建立 NuGet 套件。Next, create a NuGet package for your application.

dotnet pack

botsay.1.0.0.nupkg 檔案是在資料夾 (由 botsay.csproj 檔案中的 <PackageOutputPath> XML 值識別) 中建立的,在此範例中是 ./nupkg 資料夾。The botsay.1.0.0.nupkg file is created in the folder identified by the <PackageOutputPath> XML value from the botsay.csproj file, which in this example is the ./nupkg folder. 這可讓您輕鬆地安裝和測試。This makes it easy to install and test. 當您想要公開發行工具時,請將它上傳至 https://www.nuget.orgWhen you want to release a tool publicly, upload it to https://www.nuget.org. 在工具於 NuGet 上可供使用之後,開發人員便可使用 dotnet tool install 命令的 --global 選項來為所有使用者安裝該工具。Once the tool is available on NuGet, developers can perform a user-wide installation of the tool using the --global option of the dotnet tool install command.

既然您已經有了套件,請從該套件安裝工具:Now that you have a package, install the tool from that package:

dotnet tool install --global --add-source ./nupkg botsay

--add-source 參數會告訴 .NET Core CLI 暫時使用 ./nupkg 資料夾 (我們的 <PackageOutputPath> 資料夾) 作為 NuGet 套件的額外來源摘要。The --add-source parameter tells the .NET Core CLI to temporarily use the ./nupkg folder (our <PackageOutputPath> folder) as an additional source feed for NuGet packages. 如需安裝通用工具的詳細資訊,請參閱 .NET Core 通用工具概觀For more information about installing Global Tools, see .NET Core Global Tools overview.

如果安裝成功,則會顯示一則訊息,其中顯示用來呼叫此工具的命令以及安裝的版本,類似於下例範例:If installation is successful, a message is displayed showing the command used to call the tool and the version installed, similar to the following example:

You can invoke the tool using the following command: botsay
Tool 'botsay' (version '1.0.0') was successfully installed.

您現在應該可以輸入 botsay 並且取得工具的回應。You should now be able to type botsay and get a response from the tool.

注意

如果安裝成功,但是您無法使用 botsay 命令,您需要開啟新的終端機以重新整理路徑。If the install was successful, but you cannot use the botsay command, you may need to open a new terminal to refresh the PATH.

移除工具Remove the tool

一旦您完成工具的實驗,可以使用下列命令來將它移除:Once you're done experimenting with the tool, you can remove it with the following command:

dotnet tool uninstall -g botsay