C#でコマンドプロンプトを使ってWindowsサービスをインストールする手順
C#で作成したWindowsサービスは、そのままでは実行できません。サービスコントロールマネージャー(SCM)への登録が必要です。本記事では、Visual StudioでWindowsサービスアプリケーションを作成し、コマンドプロンプトからInstallUtil.exeを使って実際にインストール・起動するまでの一連の手順を解説します。
ステップ1:Windowsサービスアプリケーションの新規作成
まず、Visual Studioで新しいWindowsサービスアプリケーションプロジェクトを作成します。

ステップ2:インストーラーの追加
Windowsサービスを実行するには、サービスをサービスコントロールマネージャーに登録するためのインストーラーが必要です。Service1.cs[デザイン]画面を右クリックし、「インストーラーの追加」を選択してください。


ステップ3:ProjectInstallerのコード編集
ProjectInstaller.cs[デザイン]を右クリックし、「コードの表示」を選択します。生成されたコードは以下のようになっています。
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;
namespace DemoWindowsService{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer{
public ProjectInstaller(){
InitializeComponent();
}
}
}
F12キーを押してInitializeComponentメソッドの実装に移動し、ここにサービス名と説明を追加します。これらはインストール時にWindowsサービスの名称として表示されます。
private void InitializeComponent(){
this.serviceProcessInstaller1 = new
System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account =
System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.Description = "My Demo Service";
this.serviceInstaller1.ServiceName = "DemoService";
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
ステップ4:ログ出力処理の実装
次に、Service1.csクラスに、テキストファイルへログデータを書き込む以下のロジックを追加します。このサンプルでは5秒ごとにタイマーイベントが発生し、サービスの起動・停止・再呼び出しの時刻をログとして記録します。
using System;
using System.IO;
using System.ServiceProcess;
using System.Timers;
namespace DemoWindowsService{
public partial class Service1 : ServiceBase{
Timer timer = new Timer();
public Service1(){
InitializeComponent();
}
protected override void OnStart(string[] args){
WriteToFile("Service started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000;
timer.Enabled = true;
}
protected override void OnStop(){
WriteToFile("Service stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e){
WriteToFile("Service recall at " + DateTime.Now);
}
public void WriteToFile(string Message){
string path = @"D:\Demo";
if (!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
string filepath = @"D:\Demo\Log.txt";
if (!File.Exists(filepath)){
using (StreamWriter sw = File.CreateText(filepath)){
sw.WriteLine(Message);
}
} else {
using (StreamWriter sw = File.AppendText(filepath)){
sw.WriteLine(Message);
}
}
}
}
}
ステップ5:コマンドプロンプトからのインストール
それでは、コマンドプロンプトを使ってWindowsサービスをインストールしましょう。管理者権限でコマンドプロンプトを開き、まず.NET Frameworkのディレクトリへ移動します。
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

続いて、Windowsサービスのexeファイルが存在するフォルダを指定し、以下のコマンドでInstallUtil.exeを実行します。
InstallUtil.exe C:\Users\[UserName] source\repos\DemoWindowsService\DemoWindowsService\bin\Debug\ DemoWindowsService.exe


インストール結果の確認
Windowsのアプリケーションメニューから「サービス」を開きます。


サービス一覧に「DemoService」が表示され、正常にインストールされて起動していることが確認できます。
以下の出力を見ると、サービスが実行中であり、テキストファイルに期待どおりログが書き込まれていることがわかります。

-
Windows 10のコマンドプロンプトでコピー&ペーストする方法【初心者向け完全ガイド】
コマンドプロンプトは、Windowsオペレーティングシステムの中でも最も強力なツールのひとつです。WindowsのGUI(グラフィカルユーザーインターフェース)では実現できない操作も可能ですが、コマンドプロンプト内でのコピー&ペーストには不便な点がありました。このガイドでは、コマンドプロンプトでテキストをコピーする方法と、必要に応じてコマンドラインを貼り付ける方法をわかりやすく解説します。 Windows 10のコマンドプロンプトでコピーする方法 通常、Windows 10の各種アプリケーションでは「Ctrl + C」キーでファイルやテキストなどをコピーできますが、コマンドプロンプトではこの標
-
Windows 10のコマンドプロンプトでディレクトリを変更する方法|cdコマンドの使い方を徹底解説
コマンドプロンプト(Command Prompt)は、Windowsに搭載された非常に便利なユーティリティの一つです。さまざまなコマンドを実行したり、エラーのトラブルシューティングを行ったりできるため、Microsoftユーザーコミュニティでは「CMD」という名称で広く親しまれています。テキストベースのユーザーインターフェースを通じて、高度な管理操作も実行可能です。本記事では、コマンドプロンプト(CMD)でディレクトリを変更する手順を、初心者にもわかりやすくステップごとに解説します。 CMDを使えば、複数のウィンドウを行き来することなく、直接ディレクトリを操作できます。その鍵となるのが「cd」