C#编程之尝鲜.net core2.1 ——编写一个global tool
小标 2019-04-08 来源 : 阅读 1098 评论 0

摘要:本文主要向大家介绍了C#编程之尝鲜.net core2.1 ——编写一个global tool,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之尝鲜.net core2.1 ——编写一个global tool,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

C#编程之尝鲜.net core2.1 ——编写一个global tool

用过npm开发都知道,npm包都可以以全局的方式安装,例如安装一个http-server服务,可以使用npm i http-server -g来将http-server包安装到全局环境。安装完之后,就可以通过cmd或者powershell运行全局工具http-server命令,来使用静态托管服务。dotnet tool 就是一个类似npm全局工具的新特性,在.net core2.1正式加入。它的详细使用方法可在微软官方文档查看,本文主要介绍如何编写一个global tool并发布至nuget。

安装.net core 2.1

安装最新版.net core SDK 可前往DotNet官方站点的下载页面,下载完成后双击安装即可。安装完成后打开cmd运行dotnet --version 返回版本大于或等于2.1.300表示安装成功。

安装global tool 项目模板

打开cmd 键入dotnet new --install McMaster.DotNet.GlobalTool.Templates安装完成后运行dotnet new

模板                                                短名称                语言                标记

----------------------------------------------------------------------------------------------------------------------------

Console Application                               console            [C#], F#, VB      Common/Console

Class library                                     classlib           [C#], F#, VB      Common/Library

.NET Core Global Console Tool                     global-tool        [C#]              Console/Empty

Unit Test Project                                 mstest             [C#], F#, VB      Test/MSTest

xUnit Test Project                                xunit              [C#], F#, VB      Test/xUnit

Razor Page                                        page               [C#]              Web/ASP.NET

MVC ViewImports                                   viewimports        [C#]              Web/ASP.NET

MVC ViewStart                                     viewstart          [C#]              Web/ASP.NET

ASP.NET Core Empty                                web                [C#], F#          Web/Empty

ASP.NET Core Web App (Model-View-Controller)      mvc                [C#], F#          Web/MVC

ASP.NET Core Web App                              razor              [C#]              Web/MVC/Razor Pages

ASP.NET Core with Angular                         angular            [C#]              Web/MVC/SPA

ASP.NET Core with React.js                        react              [C#]              Web/MVC/SPA

ASP.NET Core with React.js and Redux              reactredux         [C#]              Web/MVC/SPA

Razor Class Library                               razorclasslib      [C#]              Web/Razor/Library/Razor Class Library

ASP.NET Core Web API                              webapi             [C#], F#          Web/WebAPI

global.json file                                  globaljson                           Config

NuGet Config                                      nugetconfig                          Config

Web Config                                        webconfig                            Config

Solution File                                     sln                                  Solution

多出一个global-tool模板

.NET Core Global Console Tool    global-tool     
 [C#]              Console/Empty

编写一个网页下载工具

接下来通过编写一个网页下载的小工具来演示global tool的创建过程,此小工具的功能是根据网址,下载相应的页面html并保存为文件。

首先新建一个WebDownloader文件夹。在文件夹中运行dotnet new global-tool生成项目如下

objProgram.csWebDownloader.csproj

打开WebDownloader.csproj修改为

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

  <PropertyGroup>
    <ToolCommandName>web-downloader</ToolCommandName>
    <PackAsTool>True</PackAsTool>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include=""McMaster.Extensions.CommandLineUtils"" Version=""2.2.3"" />
  </ItemGroup></Project>

打开Program.cs修改为

using System;

using System.ComponentModel.DataAnnotations;

using System.IO;

using System.Net.Http;

using McMaster.Extensions.CommandLineUtils;


namespace WebDownloader

{

    [Command(Description = ""网页下载小工具"")]

    class Program

    {

        public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);


        [Argument(0, Description = ""网址"")]

        [Required]

        public string Url { get; }


        [Option(Description = ""保存路径"")]

        public string Path { get; } = ""./"";


        [Option(Description = ""文件名"")]

        public string Name { get; } = ""content.txt"";


        private int OnExecute()

        {

            var client = new HttpClient();

            var content = client.GetStringAsync(Url).Result;

            var path = System.IO.Path.Combine(Path, Name);

            File.WriteAllText(path, content);

            return 0;

        }

    }

}

修改完成后全部保存文件,运行dotnet pack -o ./会在项目根目录生成一个WebDownloader.1.0.0.nupkg包。此包就是最终的nuget包,可上传至nuget.org共享。

为了测试,我们直接将此包安装至本地计算机。运行dotnet tool install WebDownloader -g --add-source ./完成安装。运行web-downloader -h可以看到项目帮助文档

网页下载小工具Usage: WebDownloader [arguments] [options]Arguments:
  Url               网址Options:
  -p|--path <PATH>  保存路径
  -n|--name <NAME>  文件名
  -?|-h|--help      Show help information

运行web-downloader //www.sina.com后我们发现项目根目录生成了一个content.txt文件内容为新浪的首页html

<!DOCTYPE html><!-- [ published at 2018-05-31 23:35:00 ] --><html><head>
    <meta http-equiv=""Content-type"" content=""text/html; charset=utf-8"" />
    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" />
    <title>新浪首页</title>
    <meta name=""keywords"" content=""新浪,新浪网,SINA,sina,sina.com.cn,新浪首页,门户,资讯"" />
    <meta name=""description"" content=""新浪网为全球用户24小时提供全面及时的中文资讯,内容覆盖国内外突发新闻事件、体坛赛事、娱乐时尚、产业资讯、实用信息等,设有新闻、体育、娱乐、财经、科技、房产、汽车等30多个内容频道,同时开设博客、视频、论坛等自由互动交流空间。"" />
    <link rel=""mask-icon"" sizes=""any"" href=""//www.sina.com.cn/favicon.svg"" color=""red"">
    <meta name=""stencil"" content=""PGLS000022"" />
    <meta name=""publishid"" content=""30,131,1"" />
    <meta name=""verify-v1"" content=""6HtwmypggdgP1NLw7NOuQBI2TW8+CfkYCoyeB8IDbn8="" />
    <meta name=""360-site-verification"" content=""63349a2167ca11f4b9bd9a8d48354541"" />
    <meta name=""application-name"" content=""新浪首页""/>
    <meta name =""msapplication-TileImage"" content=""//i1.sinaimg.cn/dy/deco/2013/0312/logo.png""/>
    <meta name=""msapplication-TileColor"" content=""#ffbf27""/>
    <meta name=""sogou_site_verification"" content=""Otg5irx9wL""/><link rel=""apple-touch-icon"" href=""//i3.sinaimg.cn/home/2013/0331/U586P30DT20130331093840.png"" />...
...

如果不再使用此工具通过dotnet tool uninstall WebDownloader -g卸载即可。

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程