【问题标题】:Get the assembly path but not the temporary path where the assembly is running获取程序集路径,但不获取程序集运行的临时路径
【发布时间】:2013-07-17 19:25:16
【问题描述】:

对于我正在编写的简单单元测试,我真的很头疼!

[TestFixture]
Class A
{

  [TestMethod]
  public void test()
  {
      Assembly.GetExecutingAssembly().Location // gives some temporary local path
  }

 }

我想要的只是获取程序集位置(我的项目文件夹所在的位置)的路径,而不是某个本地或临时文件夹。

如果我放一个断点,这个文件夹就是我得到的:\AppData\Local\Temp\

非常感谢任何帮助!

编辑:我尝试使用 nUnit 和 MSTest microsoft 的单元测试来执行此操作!没有任何帮助。

【问题讨论】:

  • 实际上这是在我正在测试的 dll 中使用的!但是,在单元测试期间,此路径是 Temp 文件夹的路径。由于我无法更改dll代码,所以我需要组装位置的路径!
  • 是的,当与 Nunit 一起使用时,它的行为确实很有趣。请仔细阅读我发送给您的链接。你会在里面找到你的答案。更准确地看第二个答案,获得 257 票。
  • @Koushik:感谢您的链接。但同样,请注意,我无法修改我正在运行的 dll 的代码,并且该语句就在该 dll 中!
  • 好的。如果要获取应用程序中引用的程序集的路径,可以使用Path.GetDirectoryName(Assembly.Load("AssemblyName").Location)。但是,如果您想获取主程序集的路径,这是一种错误的方法,因为您试图访问同一解决方案中不同项目的程序集路径。如您所知,当您进行引用时,会将 dll 的副本复制到本地目录,并在其上完成所有操作。因此,即使您从引用 dll 的位置删除项目,它仍然可以工作。可能这会有所帮助。

标签: c# visual-studio-2010 .net-4.0 nunit mstest


【解决方案1】:

下面的代码可以工作。

Path.GetDirectoryName(new System.Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath)

【讨论】:

    【解决方案2】:

    你试过了吗

    AppDomain.CurrentDomain.BaseDirectory   
    

    【讨论】:

    • 实际上这是在我正在测试的 dll 中使用的!但是,在单元测试期间,此路径是 Temp 文件夹的路径。由于我无法更改dll代码,所以我需要组装位置的路径!
    【解决方案3】:

    对于 ASP.Net,它不起作用。我在Why AppDomain.CurrentDomain.BaseDirectory not contains "bin" in asp.net app? 找到了一个更好的解决方案。它适用于 Win 应用程序和 ASP.Net Web 应用程序。

    public string ApplicationPath
    {
        get
        {
            if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))
            {
                return AppDomain.CurrentDomain.BaseDirectory; //exe folder for WinForms, Consoles, Windows Services
            }
            else
            {
                return AppDomain.CurrentDomain.RelativeSearchPath; //bin folder for Web Apps 
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      如果GetExecutingAssembly() 不是您期望的可执行文件,为什么不在您想要的程序集中使用已知类型。

      typeof(A).Assembly.Location;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        相关资源
        最近更新 更多