コンソールアプリがC#で実行されているディレクトリを確認するにはどうすればよいですか?
回答:
.exeファイルがあるディレクトリを取得するには:
AppDomain.CurrentDomain.BaseDirectory
現在のディレクトリを取得するには:
Environment.CurrentDirectory
System.AppContext.BaseDirectory。
アプリケーションに付与された権限、シャドウコピーが有効かどうか、その他の呼び出しと展開のオプションに応じて、さまざまな方法が機能するか、さまざまな結果が得られる可能性があるため、武器を賢く選択する必要があります。そうは言っても、以下のすべては、それが存在するマシンでローカルに実行される完全に信頼されたコンソールアプリケーションに対して同じ結果をもたらします。
Console.WriteLine( Assembly.GetEntryAssembly().Location );
Console.WriteLine( new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath );
Console.WriteLine( Assembly.GetEntryAssembly().Location );
Console.WriteLine( Environment.GetCommandLineArgs()[0] );
Console.WriteLine( Process.GetCurrentProcess().MainModule.FileName );
必要な正確な権限を確認するには、上記のメンバーのドキュメントを参照する必要があります。
Path.GetDirectoryName(Assembly.GetExecutingAssembly()。Location)
.Netコアコンソールアプリケーションプロジェクト名がDataPrepであるとしましょう。
プロジェクトベースディレクトリを取得します。
Console.WriteLine(Environment.CurrentDirectory);
出力:〜DataPrep \ bin \ Debug \ netcoreapp2.2
Get Project .csproj file directory:
string ProjectDirPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\"));
Console.WriteLine(ProjectDirPath);
出力:〜DataPrep \
AppContext.BaseDirectory.net5に使用します。