.NET Core 全局工具概述。
本主题适用于:✓ .NET Core SDK 2.1 及更高版本
创建项目
本文使用 .NET Core CLI 创建和管理项目。
首先,创建新的 .NET Core 控制台应用程序。
dotnet new console -o botsay
导航到由先前命令创建的 botsay 目录。
添加代码
Visual Studio Code)打开 Program.cs 文件。
将以下 using 指令添加到文件顶部,这有助于缩短代码以显示应用程序的版本信息。
using System.Reflection;
否则,所有这些参数都将转换为字符串并使用自动程序打印。
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));
}
创建自动程序
dotnetbot 示例。
static void ShowBot(string message)
{
string bot = $"\n {message}";
bot += @"
__________________
\
\
....
....'
....
..........
.............'..'..
................'..'.....
.......'..........'..'..'....
........'..........'..'..'.....
.'....'..'..........'..'.......'.
.'..................'... ......
. ......'......... .....
. _ __ ......
.. # ## ......
.... . .......
...... ....... ............
................ ......................
........................'................
......................'..'...... .......
.........................'..'..... .......
........ ..'.............'..'.... ..........
..'..'... ...............'....... ..........
...'...... ...... .......... ...... .......
........... ....... ........ ......
....... '...'.'. '.'.'.' ....
....... .....'.. ..'.....
.. .......... ..'........
............ ..............
............. '..............
...........'.. .'.'............
............... .'.'.............
.............'.. ..'..'...........
............... .'..............
......... ..............
.....
";
Console.WriteLine(bot);
}
测试工具
尝试使用命令行的这些变体来查看不同的结果:
dotnet run
dotnet run -- "Hello from the bot"
dotnet run -- hello from the bot
位于 -- 分隔符后的所有参数均会传递给应用程序。
安装全局工具
打开 botsay.csproj 文件,并向 <Project><PropertyGroup> 节点添加三个新的 XML 节点:
-
<PackAsTool>
[必需] 表示将打包应用程序以作为全局工具进行安装。 -
<ToolCommandName>
一个包中可以有多个工具,选择一个唯一且友好的名称有助于与同一包中的其他工具区别开来。 -
<PackageOutputPath>
NuGet 包是.NET Core CLI 全局工具用于安装你的工具的包。
<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>./nupkg</PackageOutputPath>。
接下来,创建应用程序的 NuGet 包。
dotnet pack
dotnet tool install 命令的 --global 选项在用户范围内安装该工具。
现在你已有一个包,请通过该包安装工具:
dotnet tool install --global --add-source ./nupkg botsay
.NET Core 全局工具概述。
如果安装成功,会出现一条消息,显示用于调用工具的命令以及所安装的版本,类似于以下示例:
You can invoke the tool using the following command: botsay
Tool 'botsay' (version '1.0.0') was successfully installed.
现在应能够键入 botsay,并获得来自工具的响应。
备注
如果安装已成功,但无法使用 botsay 命令,可能需要打开新的终端来刷新 PATH。
删除工具
完成工具的试验后,可以使用以下命令将其删除:
dotnet tool uninstall -g botsay
