C# 如何获取类库上的当前目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:46:35  来源:igfitidea点击:

How to get the current directory on a class library?

c#asp.netpathfilepathconfiguration-files

提问by nandos

I've been looking around but I have not found a solution for this problem: I want to create a class library that has a configuration file under a sub-directory called Configuration. I want that class library to be deployed anywhere and I want it to find its configuration files by knowing its own location.

我一直在环顾四周,但没有找到解决此问题的方法:我想创建一个类库,该类库在名为 Configuration 的子目录下有一个配置文件。我希望该类库部署在任何地方,并且我希望它通过知道自己的位置来找到它的配置文件。

Previous attempts with Assembly.GetExecutingAssembly().Locationdid not work.
It would return temp locations such as

以前的尝试Assembly.GetExecutingAssembly().Location没有奏效。
它会返回临时位置,例如

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\7c00e0a3\38789d63\assembly\dl3\9c0a23ff\18fb5feb_6ac3c901

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\7c00e0a3\38789d63\assembly\dl3\9c0a23ff\18fb5feb_6ac3c901

instead of the desired

而不是想要的

bin/Configurationpath.

bin/Configuration小路。

So:

所以:

  1. Can a class library be aware of its own location on disk?
  2. How would I go about witting test scripts for this functionality since it seems that directories change based on how you run the app (debugging inside VS, deploying on IIS, etc)
  1. 类库可以知道自己在磁盘上的位置吗?
  2. 我将如何编写此功能的测试脚本,因为目录似乎根据您运行应用程序的方式而变化(在 VS 内调试、在 IIS 上部署等)

采纳答案by Reed Copsey

This should work -

这应该有效 -

string assemblyFile = (
    new System.Uri(Assembly.GetExecutingAssembly().CodeBase)
).AbsolutePath;

回答by Rajeev Kumar

The below code worked for me to get the physical path of the Images folder in-class library file.

下面的代码对我有用,可以获取类库文件中图像文件夹的物理路径。

string fullFilePath = Path.Combine((new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath.Split(new string[] { "/bin" }, StringSplitOptions.None)[0]
                          , "@/Images/test.png");

I hope, it will help someone.

我希望,它会帮助某人。