LoginSignup
4
2

More than 1 year has passed since last update.

.NET6 単一ファイル時の実行パス取得について

Posted at

要約

単一ファイルにする場合、Assembly.Location は空文字列を返すので使えない。Assembly 系は避けた方が良いかも。

環境

.NET6
Visual Studio 2022

本題

どうも。「バーチャルためにならない改変お姉さん」の水無月せきなです。

とある VRSNS 用のツール開発にあたって WPF/.NET6 で頑張ろうとしているところなのですが、exe のパスを取る目的で Assembly.Location を使ったら、実際の環境で空文字列が返ってきました。デバッグではちゃんとパスは取れます。

違いを考えるとすると、インストーラの作成と単一ファイルになるようにしたこと。

ちょっと調べるとこの原因について言及した記事も見受けられた気がしますが、公式にこんなのがありました。

原因
単一ファイルとして発行する場合 (たとえば、プロジェクトの PublishSingleFile プロパティを true に設定する)、単一ファイル バンドル内に埋め込まれているアセンブリの Assembly.Location プロパティを呼び出すと、常に空の文字列が返されます。

ついでに、こちらにて紹介されている Assembly.CodeBaseページでは、

注意事項
Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location.

互換性維持のためにあるとのこと。Assembly.Location を使えとありますが、その Assembly.Location が空文字列を返すので実質使えない……

ということで、単一ファイルなどにしている場合で exe のパスを取りたい場合は、公式が言及している AppContext.BaseDirectory が良さそうです。ただし、こちらは最後に\ が入るようなので、適宜TrimEnd で取り除く必要があります。

参考

https://docs.microsoft.com/ja-jp/dotnet/core/deploying/single-file/warnings/il3000
https://docs.microsoft.com/ja-jp/dotnet/api/system.reflection.assembly.codebase?view=net-6.0
https://www.umayadia.com/cssample/sample0000/Sample136GetAppPath.htm

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2