コンソールアプリで実行ファイルのディレクトリのパス、ディレクトリ名を取得するコードを紹介します。
こちらの記事では、Windows Formアプリケーションで、アプリケーションの実行ディレクトリを取得するコードを紹介しました。
紹介した方法では、System.Windows.Forms.Application
オブジェクトを利用するため、コンソールアプリケーションで同様の処理を実行する場合は、
System.Windows.Forms をアプリケーションの参照に追加する必要があり、冗長になってしまいます。
この記事では、Applicationオブジェクトを利用しない方法で実行ファイルのディレクトリのパスを取得するコードを紹介します。
Applicationオブジェクトを利用せずに、実行時のパスを取得する方法には以下があります。
コンソールアプリケーションを作成し、以下のコードを作成します。
// See https://aka.ms/new-console-template for more information
using System.Reflection;
string entry_assembly_path = Assembly.GetEntryAssembly().Location;
string executing_assembly_path = Assembly.GetExecutingAssembly().Location;
string app_base_path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
string base_dir = AppContext.BaseDirectory;
string comm_path = Environment.CommandLine;
string args_path = Environment.GetCommandLineArgs()[0];
Console.WriteLine("GetEntryAssembly: "+entry_assembly_path);
Console.WriteLine("GetExecutingAssembly: " + executing_assembly_path);
Console.WriteLine("ApplicationBase: " + app_base_path);
Console.WriteLine("BaseDirectory: " + base_dir);
Console.WriteLine("CommandLine: " + comm_path);
Console.WriteLine("GetCommandLineArgs: " + args_path);
Console.ReadLine();
using System;
using System.Reflection;
namespace GetPathConsoleClassic
{
internal class Program
{
static void Main(string[] args)
{
string entry_assembly_path = Assembly.GetEntryAssembly().Location;
string executing_assembly_path = Assembly.GetExecutingAssembly().Location;
string app_base_path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
string base_dir = AppContext.BaseDirectory;
string comm_path = Environment.CommandLine;
string args_path = Environment.GetCommandLineArgs()[0];
Console.WriteLine("GetEntryAssembly: "+entry_assembly_path);
Console.WriteLine("GetExecutingAssembly: " + executing_assembly_path);
Console.WriteLine("ApplicationBase: " + app_base_path);
Console.WriteLine("BaseDirectory: " + base_dir);
Console.WriteLine("CommandLine: " + comm_path);
Console.WriteLine("GetCommandLineArgs: " + args_path);
Console.ReadLine();
}
}
}
Assembly.GetEntryAssembly() によりプロセスのアセンブリ情報を取得できます。Location
プロパティに実行ファイルのパスが設定されています。
Assembly.GetExecutingAssembly()により、現在実行中のアセンブリ情報を取得できます。Location
プロパティに実行ファイルのパスが設定されています。
AppDomain.CurrentDomain.SetupInformation.ApplicationBase プロパティにアプリケーションを含むディレクトリの名前が設定されています。
AppContext.BaseDirectory プロパティにアプリケーションが配置されているディレクトリのフルパスが設定されています。
Environment.CommandLine にプログラム名とコマンドラインに指定されたすべてのパラメーターを取得できます。
Environment.GetCommandLineArgs()[0] には、コマンドラインの最初のパラメーターである実行ファイルのパスが格納されています。
.NET 8.0のコンソールアプリケーションでの実行結果です。
.NET の場合は、コンソールアプリケーションのexeファイルではなく、dllファイルが実行ファイルのパスとして表示されます。
実行時にパラメーターが設定されている場合の結果です。CommandLine プロパティにはパラメーターの文字列も含まれていることが確認できます。
.NET Framework 4.8のコンソールアプリケーションでの実行結果です。
.NET Frameworkの場合は、コンソールアプリケーションのexeファイルのパスが実行プログラムのパスとして取得できます。
実行時にパラメーターが設定されている場合の結果です。CommandLine プロパティにはパラメーターの文字列も含まれていることが確認できます。