[.net core 3.0] Linux用のCliツール作成(単一ファイル)

新しいプロジェクトの作成

コンソールアプリ(.NET Core) -> プロジェクト名(ここでは適当にTestTool)

code

using System;

namespace TestTool {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello World!");
            foreach (var arg in args) {
                Console.WriteLine(arg);
            }
            /* end */
            Console.WriteLine("Press Any key to continue...");
            Console.ReadKey(true);
        }
    }
}

発行のプロファイルを作る

ビルド -> TestToolの発行 -> 発行先はフォルダ -> プロファイルの作成

配置モードを自己完結, ターゲットランタイムをlinux-x64に変更して保存。

単一ファイルに変更するためにprofileファイルを編集。ソリューションエクスプローラからProperties>PublishProfiles>FolderProfile.pubxmlを選択して開く。

<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121. 
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PublishProtocol>FileSystem</PublishProtocol>
    <Configuration>Release</Configuration>
    <Platform>Any CPU</Platform>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <PublishDir>bin\publish\</PublishDir>
    <RuntimeIdentifier>linux-x64</RuntimeIdentifier>
    <SelfContained>true</SelfContained>
    <PublishSingleFile>true</PublishSingleFile> <!--単一ファイル出力指定-->
  </PropertyGroup>
</Project>

PublishSingleFileを追加して保存。

発行

ビルド -> TestToolの発行 -> 発行

実行

単一ファイルと言いつつpdbファイル(Releaseビルドなのに)も出力される。作成されたlinuxバイナリ(TestTool)(76MB)をこのサーバにアップロードして実行。

[dobu@133-130-123-5 ~]$ chmod +x TestTool
[dobu@133-130-123-5 ~]$ ./TestTool hoge fuga piyo
Hello World!
hoge
fuga
piyo
Press Any key to continue...
[dobu@133-130-123-5 ~]$

明るくないsh書くよりこっちのほうが楽だなー。個人では複雑怪奇なことをlinuxでやることはないのだけど、debuggerが強力なので。単一ファイルにすることで各バージョン気にしなくてすむのが最高。ファイルサイズの肥大化は……このご時世ある程度までなら増えても別にいいだろって。

ex) https://docs.microsoft.com/ja-jp/dotnet/core/whats-new/dotnet-core-3-0#single-file-executables