如何获得程序集的路径?

时间:2023-01-14 14:41:55

Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code.

是否有方法获取当前代码所在程序集的路径?我不需要调用程序集的路径,只需要包含代码的路径。

Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.

基本上,我的单元测试需要读取一些相对于dll的xml测试文件。无论测试dll是否从TestDriven运行,我都希望路径总是正确解析。NET、MbUnit GUI或其他东西。

Edit: People seem to be misunderstanding what I'm asking.

编辑:人们似乎误解了我的要求。

My test library is located in say

我的测试库位于say。

C:\projects\myapplication\daotests\bin\Debug\daotests.dll

C:\ \项目myapplication \ daotests \ bin \ \ daotests.dll调试

and I would like to get this path:

我想走这条路:

C:\projects\myapplication\daotests\bin\Debug\

C:\ \ myapplication \ daotests \ bin \项目调试\

The three suggestions so far fail me when I run from the MbUnit Gui:

到目前为止,当我运行MbUnit Gui时,这三个建议让我失望:

  • Environment.CurrentDirectory gives c:\Program Files\MbUnit

    环境。CurrentDirectory给c:\Program Files\MbUnit

  • System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location gives C:\Documents and Settings\george\Local Settings\Temp\ ....\DaoTests.dll

    System.Reflection.Assembly.GetAssembly(typeof(DaoTests))。位置给\ Temp \ .... \ DaoTests.dll C:\Documents and Settings\george\Local设置

  • System.Reflection.Assembly.GetExecutingAssembly().Location gives the same as the previous.

    System.Reflection.Assembly.GetExecutingAssembly()。位置与前一个相同。

26 个解决方案

#1


880  

I've defined the following property as we use this often in unit testing.

我定义了以下属性,因为我们在单元测试中经常使用它。

public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

The Assembly.Location property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use CodeBase which gives you the path in URI format, then UriBuild.UnescapeDataString removes the File:// at the beginning, and GetDirectoryName changes it to the normal windows format.

大会。Location属性在使用NUnit(从临时文件夹运行程序集)时有时会给您带来一些有趣的结果,因此我更喜欢使用代码基,它以URI格式给出路径,然后使用UriBuild。UnescapeDataString在开头删除文件://,GetDirectoryName将其更改为普通的windows格式。

#2


278  

Does this help?

这有帮助吗?

//get the full location of the assembly with DaoTests in it
string fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;

//get the folder that's in
string theDirectory = Path.GetDirectoryName( fullPath );

#3


268  

It's as simple as this:

就这么简单:

var dir = AppDomain.CurrentDomain.BaseDirectory;

#4


61  

Same as John's answer, but a slightly less verbose extension method.

和John的答案一样,只是稍微不太详细的扩展方法。

public static string GetDirectoryPath(this Assembly assembly)
{
    string filePath = new Uri(assembly.CodeBase).LocalPath;
    return Path.GetDirectoryName(filePath);            
}

Now you can do:

现在你能做的:

var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();

or if you prefer:

或者如果你喜欢:

var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();

#5


43  

The only solution that worked for me when using CodeBase and UNC Network shares was:

在使用代码库和UNC网络共享时,唯一对我有效的解决方案是:

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

It also works with normal URIs too.

它也适用于普通uri。

#6


31  

This should work, unless the assembly is shadow copied:

这应该是可行的,除非程序集是影子拷贝的:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location

#7


11  

I suspect that the real issue here is that your test runner is copying your assembly to a different location. There's no way at runtime to tell where the assembly was copied from, but you can probably flip a switch to tell the test runner to run the assembly from where it is and not to copy it to a shadow directory.

我怀疑这里真正的问题是,您的测试运行器正在将程序集复制到另一个位置。在运行时没有办法告诉程序集是从哪里复制的,但是您可以翻转一个开关来告诉测试运行器从它所在的位置运行程序集,而不是将它复制到影子目录。

Such a switch is likely to be different for each test runner, of course.

当然,这种切换对于每个测试运行器可能是不同的。

Have you considered embedding your XML data as resources inside your test assembly?

您是否考虑将XML数据作为资源嵌入到测试程序集中?

#8


11  

What about this:

这个:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

#9


9  

AppDomain.CurrentDomain.BaseDirectory

works with MbUnit GUI.

与运行GUI。

#10


7  

var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var assemblyPath = assembly.GetFiles()[0].Name;
var assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);

#11


7  

Here is a VB.NET port of John Sibly's code. Visual Basic is not case sensitive, so a couple of his variable names were colliding with type names.

这是一个VB。John振振铃代码的网络端口。Visual Basic不是区分大小写的,所以他的几个变量名与类型名发生冲突。

Public Shared ReadOnly Property AssemblyDirectory() As String
    Get
        Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase
        Dim uriBuilder As New UriBuilder(codeBase)
        Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)
        Return Path.GetDirectoryName(assemblyPath)
    End Get
End Property

#12


6  

I've been using Assembly.CodeBase instead of Location:

我一直在使用组装。代码库,而不是位置:

Assembly a;
a = Assembly.GetAssembly(typeof(DaoTests));
string s = a.CodeBase.ToUpper(); // file:///c:/path/name.dll
Assert.AreEqual(true, s.StartsWith("FILE://"), "CodeBase is " + s);
s = s.Substring(7, s.LastIndexOf('/') - 7); // 7 = "file://"
while (s.StartsWith("/")) {
    s = s.Substring(1, s.Length - 1);
}
s = s.Replace("/", "\\");

It's been working, but I'm no longer sure it is 100% correct. The page at http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx says:

它一直在工作,但我不再确定它是100%正确的。http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx的页面说:

"The CodeBase is a URL to the place where the file was found, while the Location is the path where it was actually loaded. For example, if the assembly was downloaded from the internet, its CodeBase may start with "http://", but its Location may start with "C:\". If the file was shadow-copied, the Location would be the path to the copy of the file in the shadow copy dir. It’s also good to know that the CodeBase is not guaranteed to be set for assemblies in the GAC. Location will always be set for assemblies loaded from disk, however."

“代码库是找到文件的地方的URL,而位置是实际加载文件的路径。”例如,如果程序集是从internet下载的,它的代码基可能以“http://”开头,但是它的位置可能以“C:\”开头。如果文件是影子拷贝,那么位置将是影子拷贝目录中文件拷贝的路径。同样值得注意的是,代码基并不能保证为GAC中的程序集设置。但是,从磁盘加载的程序集的位置将始终被设置。

You may want to use CodeBase instead of Location.

您可能希望使用代码库而不是位置。

#13


6  

In all these years, nobody has actually mentioned this one. A trick I learned from the awesome ApprovalTests project. The trick is that you use the debugging information in the assembly to find the original directory.

这些年来,没有人真正提到过这个。这是我从令人敬畏的ApprovalTests项目中学到的一个技巧。诀窍是使用程序集中的调试信息来查找原始目录。

This will not work in RELEASE mode, nor with optimizations enabled, nor on a machine different from the one it was compiled on.

这不会在发布模式下工作,也不会在启用了优化的情况下工作,也不会在与编译时不同的机器上工作。

But this will get you paths that are relative to the location of the source code file you call it from

但是这将获得与您调用它的源代码文件的位置相关的路径

public static class PathUtilities
{
    public static string GetAdjacentFile(string relativePath)
    {
        return GetDirectoryForCaller(1) + relativePath;
    }
    public static string GetDirectoryForCaller()
    {
        return GetDirectoryForCaller(1);
    }


    public static string GetDirectoryForCaller(int callerStackDepth)
    {
        var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);
        return GetDirectoryForStackFrame(stackFrame);
    }

    public static string GetDirectoryForStackFrame(StackFrame stackFrame)
    {
        return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;
    }
}

#14


5  

The current directory where you exist.

当前存在的目录。

Environment.CurrentDirectory;  // This is the current directory of your application

If you copy the .xml file out with build you should find it.

如果您用build复制.xml文件,您应该会找到它。

or

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));

// The location of the Assembly
assembly.Location;

#15


5  

As far as I can tell, most of the other answers have a few problems.

据我所知,其他大多数答案都有一些问题。

The correct way to do this for a disk-based (as opposed to web-based), non-GACed assembly is to use the currently executing assembly's CodeBase property.

对于基于磁盘(而不是基于web的)的、不带支撑的程序集,正确的做法是使用当前正在执行的程序集的代码基属性。

This returns a URL (file://). Instead of messing around with string manipulation or UnescapeDataString, this can be converted with minimal fuss by leveraging the LocalPath property of Uri.

这将返回一个URL(文件://)。通过利用Uri的LocalPath属性,不需要对字符串操作或无法逃避的datastring乱涂乱画,可以将其转换为最少的麻烦。

var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
var directoryPath = Path.GetDirectoryName(filePathToCodeBase);

#16


5  

How about this ...

这个怎么样…

string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Then just hack off what you do not need

然后把你不需要的东西砍下来

#17


2  

You can get the bin path by AppDomain.CurrentDomain.RelativeSearchPath

可以通过AppDomain.CurrentDomain.RelativeSearchPath获得bin路径

#18


2  

All of the proposed answers work when the developer can change the code to include the required snippet, but if you wanted to do this without changing any code you could use Process Explorer.

当开发人员可以更改代码以包含所需的代码片段时,所有建议的答案都是可行的,但是如果您想在不更改任何代码的情况下这样做,您可以使用Process Explorer。

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

它将列出系统上的所有执行dll,您可能需要确定运行应用程序的进程id,但这通常并不太难。

I've written a full description of how do this for a dll inside II - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

我已经写了一个完整的描述,它是如何在II - http://nodogmablog.bryanhogan.net/2016/09/locating- - - - -运行- - -运行- - -运行- - -web-server/上完成的。

#19


2  

in a windows form app, you can simply use Application.StartupPath

在windows窗体应用程序中,只需使用Application.StartupPath

but for DLLs and console apps the code is much harder to remember...

但是对于dll和控制台应用程序来说,代码更难记住……

string slash = Path.DirectorySeparatorChar.ToString();
string root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

root += slash;
string settingsIni = root + "settings.ini"

#20


1  

string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);

#21


0  

This is what I came up with. In between web projects, unit tests (nunit and resharper test runner); I found this worked for me.

这就是我想到的。在web项目之间,单元测试(nunit和resharper test runner);我发现这对我很有效。

I have been looking for code to detect what configuration the build is in, Debug/Release/CustomName. Alas, the #if DEBUG. So if someone can improve that!

我一直在寻找代码来检测构建所在的配置,调试/发布/定制名称。唉,如果调试#。所以如果有人能改进的话!

Feel free to edit and improve.

请随意编辑和改进。

Getting app folder. Useful for web roots, unittests to get the folder of test files.

应用程序文件夹。对web根非常有用,unittests用来获取测试文件的文件夹。

public static string AppPath
{
    get
    {
        DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

        while (appPath.FullName.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
                || appPath.FullName.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            appPath = appPath.Parent;
        }
        return appPath.FullName;
    }
}

Getting bin folder: Useful for executing assemblies using reflection. If files are copied there due to build properties.

获取bin文件夹:用于使用反射执行程序集。如果由于构建属性而复制文件。

public static string BinPath
{
    get
    {
        string binPath = AppDomain.CurrentDomain.BaseDirectory;

        if (!binPath.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
            && !binPath.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            binPath = Path.Combine(binPath, "bin");
            //-- Please improve this if there is a better way
            //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.
#if DEBUG
            if (Directory.Exists(Path.Combine(binPath, "Debug"))) 
                        binPath = Path.Combine(binPath, "Debug");
#else
            if (Directory.Exists(Path.Combine(binPath, "Release"))) 
                        binPath = Path.Combine(binPath, "Release");
#endif
        }
            return binPath;
    }
}

#22


0  

This should work:

这应该工作:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly asm = Assembly.GetCallingAssembly();
String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);

string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");

I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).

我使用它来部署DLL文件库以及一些配置文件(这是在DLL文件中使用log4net)。

#23


0  

I find my solution adequate for the retrieval of the location.

我发现我的解决方案足够检索位置。

var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;

#24


0  

I got the same behaviour in the NUnit in the past. By default NUnit copies your assembly into the temp directory. You can change this behaviour in the NUnit settings:

我过去在NUnit也有同样的行为。默认情况下,NUnit将程序集复制到临时目录中。您可以在NUnit设置中更改此行为:

如何获得程序集的路径?

Maybe TestDriven.NET and MbUnit GUI have the same settings.

也许TestDriven。NET和MbUnit GUI具有相同的设置。

#25


-2  

I use this to get the path to the Bin Directory:

我用这个来获取Bin目录的路径:

var i = Environment.CurrentDirectory.LastIndexOf(@"\");
var path = Environment.CurrentDirectory.Substring(0,i); 

You get this result:

你得到这个结果:

"c:\users\ricooley\documents\visual studio 2010\Projects\Windows_Test_Project\Windows_Test_Project\bin"

“c:\ \ ricooley \用户文档\ visual studio 2010 \ Windows_Test_Project \ Windows_Test_Project \ bin \项目”

#26


-3  

Web application?

Web应用程序?

Server.MapPath("~/MyDir/MyFile.ext")

#1


880  

I've defined the following property as we use this often in unit testing.

我定义了以下属性,因为我们在单元测试中经常使用它。

public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

The Assembly.Location property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use CodeBase which gives you the path in URI format, then UriBuild.UnescapeDataString removes the File:// at the beginning, and GetDirectoryName changes it to the normal windows format.

大会。Location属性在使用NUnit(从临时文件夹运行程序集)时有时会给您带来一些有趣的结果,因此我更喜欢使用代码基,它以URI格式给出路径,然后使用UriBuild。UnescapeDataString在开头删除文件://,GetDirectoryName将其更改为普通的windows格式。

#2


278  

Does this help?

这有帮助吗?

//get the full location of the assembly with DaoTests in it
string fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;

//get the folder that's in
string theDirectory = Path.GetDirectoryName( fullPath );

#3


268  

It's as simple as this:

就这么简单:

var dir = AppDomain.CurrentDomain.BaseDirectory;

#4


61  

Same as John's answer, but a slightly less verbose extension method.

和John的答案一样,只是稍微不太详细的扩展方法。

public static string GetDirectoryPath(this Assembly assembly)
{
    string filePath = new Uri(assembly.CodeBase).LocalPath;
    return Path.GetDirectoryName(filePath);            
}

Now you can do:

现在你能做的:

var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();

or if you prefer:

或者如果你喜欢:

var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();

#5


43  

The only solution that worked for me when using CodeBase and UNC Network shares was:

在使用代码库和UNC网络共享时,唯一对我有效的解决方案是:

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

It also works with normal URIs too.

它也适用于普通uri。

#6


31  

This should work, unless the assembly is shadow copied:

这应该是可行的,除非程序集是影子拷贝的:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location

#7


11  

I suspect that the real issue here is that your test runner is copying your assembly to a different location. There's no way at runtime to tell where the assembly was copied from, but you can probably flip a switch to tell the test runner to run the assembly from where it is and not to copy it to a shadow directory.

我怀疑这里真正的问题是,您的测试运行器正在将程序集复制到另一个位置。在运行时没有办法告诉程序集是从哪里复制的,但是您可以翻转一个开关来告诉测试运行器从它所在的位置运行程序集,而不是将它复制到影子目录。

Such a switch is likely to be different for each test runner, of course.

当然,这种切换对于每个测试运行器可能是不同的。

Have you considered embedding your XML data as resources inside your test assembly?

您是否考虑将XML数据作为资源嵌入到测试程序集中?

#8


11  

What about this:

这个:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

#9


9  

AppDomain.CurrentDomain.BaseDirectory

works with MbUnit GUI.

与运行GUI。

#10


7  

var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var assemblyPath = assembly.GetFiles()[0].Name;
var assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);

#11


7  

Here is a VB.NET port of John Sibly's code. Visual Basic is not case sensitive, so a couple of his variable names were colliding with type names.

这是一个VB。John振振铃代码的网络端口。Visual Basic不是区分大小写的,所以他的几个变量名与类型名发生冲突。

Public Shared ReadOnly Property AssemblyDirectory() As String
    Get
        Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase
        Dim uriBuilder As New UriBuilder(codeBase)
        Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)
        Return Path.GetDirectoryName(assemblyPath)
    End Get
End Property

#12


6  

I've been using Assembly.CodeBase instead of Location:

我一直在使用组装。代码库,而不是位置:

Assembly a;
a = Assembly.GetAssembly(typeof(DaoTests));
string s = a.CodeBase.ToUpper(); // file:///c:/path/name.dll
Assert.AreEqual(true, s.StartsWith("FILE://"), "CodeBase is " + s);
s = s.Substring(7, s.LastIndexOf('/') - 7); // 7 = "file://"
while (s.StartsWith("/")) {
    s = s.Substring(1, s.Length - 1);
}
s = s.Replace("/", "\\");

It's been working, but I'm no longer sure it is 100% correct. The page at http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx says:

它一直在工作,但我不再确定它是100%正确的。http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx的页面说:

"The CodeBase is a URL to the place where the file was found, while the Location is the path where it was actually loaded. For example, if the assembly was downloaded from the internet, its CodeBase may start with "http://", but its Location may start with "C:\". If the file was shadow-copied, the Location would be the path to the copy of the file in the shadow copy dir. It’s also good to know that the CodeBase is not guaranteed to be set for assemblies in the GAC. Location will always be set for assemblies loaded from disk, however."

“代码库是找到文件的地方的URL,而位置是实际加载文件的路径。”例如,如果程序集是从internet下载的,它的代码基可能以“http://”开头,但是它的位置可能以“C:\”开头。如果文件是影子拷贝,那么位置将是影子拷贝目录中文件拷贝的路径。同样值得注意的是,代码基并不能保证为GAC中的程序集设置。但是,从磁盘加载的程序集的位置将始终被设置。

You may want to use CodeBase instead of Location.

您可能希望使用代码库而不是位置。

#13


6  

In all these years, nobody has actually mentioned this one. A trick I learned from the awesome ApprovalTests project. The trick is that you use the debugging information in the assembly to find the original directory.

这些年来,没有人真正提到过这个。这是我从令人敬畏的ApprovalTests项目中学到的一个技巧。诀窍是使用程序集中的调试信息来查找原始目录。

This will not work in RELEASE mode, nor with optimizations enabled, nor on a machine different from the one it was compiled on.

这不会在发布模式下工作,也不会在启用了优化的情况下工作,也不会在与编译时不同的机器上工作。

But this will get you paths that are relative to the location of the source code file you call it from

但是这将获得与您调用它的源代码文件的位置相关的路径

public static class PathUtilities
{
    public static string GetAdjacentFile(string relativePath)
    {
        return GetDirectoryForCaller(1) + relativePath;
    }
    public static string GetDirectoryForCaller()
    {
        return GetDirectoryForCaller(1);
    }


    public static string GetDirectoryForCaller(int callerStackDepth)
    {
        var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);
        return GetDirectoryForStackFrame(stackFrame);
    }

    public static string GetDirectoryForStackFrame(StackFrame stackFrame)
    {
        return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;
    }
}

#14


5  

The current directory where you exist.

当前存在的目录。

Environment.CurrentDirectory;  // This is the current directory of your application

If you copy the .xml file out with build you should find it.

如果您用build复制.xml文件,您应该会找到它。

or

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));

// The location of the Assembly
assembly.Location;

#15


5  

As far as I can tell, most of the other answers have a few problems.

据我所知,其他大多数答案都有一些问题。

The correct way to do this for a disk-based (as opposed to web-based), non-GACed assembly is to use the currently executing assembly's CodeBase property.

对于基于磁盘(而不是基于web的)的、不带支撑的程序集,正确的做法是使用当前正在执行的程序集的代码基属性。

This returns a URL (file://). Instead of messing around with string manipulation or UnescapeDataString, this can be converted with minimal fuss by leveraging the LocalPath property of Uri.

这将返回一个URL(文件://)。通过利用Uri的LocalPath属性,不需要对字符串操作或无法逃避的datastring乱涂乱画,可以将其转换为最少的麻烦。

var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
var directoryPath = Path.GetDirectoryName(filePathToCodeBase);

#16


5  

How about this ...

这个怎么样…

string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Then just hack off what you do not need

然后把你不需要的东西砍下来

#17


2  

You can get the bin path by AppDomain.CurrentDomain.RelativeSearchPath

可以通过AppDomain.CurrentDomain.RelativeSearchPath获得bin路径

#18


2  

All of the proposed answers work when the developer can change the code to include the required snippet, but if you wanted to do this without changing any code you could use Process Explorer.

当开发人员可以更改代码以包含所需的代码片段时,所有建议的答案都是可行的,但是如果您想在不更改任何代码的情况下这样做,您可以使用Process Explorer。

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

它将列出系统上的所有执行dll,您可能需要确定运行应用程序的进程id,但这通常并不太难。

I've written a full description of how do this for a dll inside II - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

我已经写了一个完整的描述,它是如何在II - http://nodogmablog.bryanhogan.net/2016/09/locating- - - - -运行- - -运行- - -运行- - -web-server/上完成的。

#19


2  

in a windows form app, you can simply use Application.StartupPath

在windows窗体应用程序中,只需使用Application.StartupPath

but for DLLs and console apps the code is much harder to remember...

但是对于dll和控制台应用程序来说,代码更难记住……

string slash = Path.DirectorySeparatorChar.ToString();
string root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

root += slash;
string settingsIni = root + "settings.ini"

#20


1  

string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);

#21


0  

This is what I came up with. In between web projects, unit tests (nunit and resharper test runner); I found this worked for me.

这就是我想到的。在web项目之间,单元测试(nunit和resharper test runner);我发现这对我很有效。

I have been looking for code to detect what configuration the build is in, Debug/Release/CustomName. Alas, the #if DEBUG. So if someone can improve that!

我一直在寻找代码来检测构建所在的配置,调试/发布/定制名称。唉,如果调试#。所以如果有人能改进的话!

Feel free to edit and improve.

请随意编辑和改进。

Getting app folder. Useful for web roots, unittests to get the folder of test files.

应用程序文件夹。对web根非常有用,unittests用来获取测试文件的文件夹。

public static string AppPath
{
    get
    {
        DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

        while (appPath.FullName.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
                || appPath.FullName.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            appPath = appPath.Parent;
        }
        return appPath.FullName;
    }
}

Getting bin folder: Useful for executing assemblies using reflection. If files are copied there due to build properties.

获取bin文件夹:用于使用反射执行程序集。如果由于构建属性而复制文件。

public static string BinPath
{
    get
    {
        string binPath = AppDomain.CurrentDomain.BaseDirectory;

        if (!binPath.Contains(@"\bin\", StringComparison.CurrentCultureIgnoreCase)
            && !binPath.EndsWith(@"\bin", StringComparison.CurrentCultureIgnoreCase))
        {
            binPath = Path.Combine(binPath, "bin");
            //-- Please improve this if there is a better way
            //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.
#if DEBUG
            if (Directory.Exists(Path.Combine(binPath, "Debug"))) 
                        binPath = Path.Combine(binPath, "Debug");
#else
            if (Directory.Exists(Path.Combine(binPath, "Release"))) 
                        binPath = Path.Combine(binPath, "Release");
#endif
        }
            return binPath;
    }
}

#22


0  

This should work:

这应该工作:

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly asm = Assembly.GetCallingAssembly();
String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);

string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");

I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).

我使用它来部署DLL文件库以及一些配置文件(这是在DLL文件中使用log4net)。

#23


0  

I find my solution adequate for the retrieval of the location.

我发现我的解决方案足够检索位置。

var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;

#24


0  

I got the same behaviour in the NUnit in the past. By default NUnit copies your assembly into the temp directory. You can change this behaviour in the NUnit settings:

我过去在NUnit也有同样的行为。默认情况下,NUnit将程序集复制到临时目录中。您可以在NUnit设置中更改此行为:

如何获得程序集的路径?

Maybe TestDriven.NET and MbUnit GUI have the same settings.

也许TestDriven。NET和MbUnit GUI具有相同的设置。

#25


-2  

I use this to get the path to the Bin Directory:

我用这个来获取Bin目录的路径:

var i = Environment.CurrentDirectory.LastIndexOf(@"\");
var path = Environment.CurrentDirectory.Substring(0,i); 

You get this result:

你得到这个结果:

"c:\users\ricooley\documents\visual studio 2010\Projects\Windows_Test_Project\Windows_Test_Project\bin"

“c:\ \ ricooley \用户文档\ visual studio 2010 \ Windows_Test_Project \ Windows_Test_Project \ bin \项目”

#26


-3  

Web application?

Web应用程序?

Server.MapPath("~/MyDir/MyFile.ext")