C# 在 Web 和命令行应用程序中查找 xml 资源的文件位置

C# find file location of xml resource both in web and command line app

我正在使用 .NET Standard 2.0 构建一个库。我有 1 个资源文件 (xml) 需要从磁盘加载。资源文件无法嵌入,部署后管理员可自由更改。

该库由十几个应用程序共享。一些网络应用程序,一些 winform 或命令行应用程序。资源文件在 Visual Studio 中设置为“Content”“Always copy”,所以它总是在 bin 文件夹中我的 DLL 旁边。该库永远不知道它是否被命令行或 Web 应用程序引用。但是我怎样才能找到资源的位置 xml?

Assembly.GetExecutingAssemply()。位置:当从 IIS Express 运行 时,returns 一些奇怪的临时文件夹。

Environment.GetCurrentDirectory(): returns C:\Program Files (x86)\IIS Express\

System.Web.Hosting.HostingEnvironment.MapPath("~/bin"): 在库中不可用。

也欢迎任何绕过该问题的替代解决方案,只要管理员可以在部署后更改资源文件。

AppContext.BaseDirectory 属性 非常适合这个:

Gets the file path of the base directory that the assembly resolver uses to probe for assemblies.