코드가 들어 있는 어셈블리의 경로를 얻으려면 어떻게 하나요?

현재 코드가 있는 어셈블리의 경로를 가져올 수 있는 방법이 있나요? 호출하는 어셈블리의 경로가 아니라 코드가 포함된 어셈블리의 경로를 원합니다.

기본적으로 내 단위 테스트는 dll에 상대적인 위치에 있는 일부 XML 테스트 파일을 읽어야 합니다. 테스트 dll이 TestDriven.NET에서 실행되는지, MbUnit GUI에서 실행되는지 또는 다른 곳에서 실행되는지에 관계없이 경로가 항상 올바르게 확인되기를 원합니다.

편집: 사람들이 제가 묻는 내용을 오해하고 있는 것 같습니다.

내 테스트 라이브러리는 다음과 같은 위치에 있습니다.

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

에 있으며 이 경로를 얻고 싶습니다:

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

지금까지 세 가지 제안은 MbUnit Gui에서 실행할 때 실패합니다:

  • 환경 .현재 디렉토리 는 c:\프로그램 파일\MbUnit을 제공합니다.

  • System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).LocationC:\Documents 및 Settings\george\Local Settings\Temp\ ....\DaoTests.dll를 제공합니다.

  • System.Reflection.Assembly.GetExecutingAssembly().Location 는 이전과 동일한 결과를 제공합니다.

질문에 대한 의견 (6)
해결책

우리가 사용하는 경우에 따라, 다음과 같은 속성을 잘 정의된 i& # 39 이 유닛 테스트.

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);
    }
}

이 결과 '속성' 아서 블라이드로카션 보기입니다 사용할 때 가끔 좀 이상한 누니스 (여기서 어셈블리들 에서 실행하십시오 임시 폴더) 의 경로를 확보할 수 있으므로 사용을 선호하지만, 그래서 '코드베이스' 형식 '열린우리당' 이 '와', '처음부터 관심용 우리브uild.런스카페다타스트링 절감뿐만 File:// 제드리스토리나미 일반 indows 형식' 로 바뀝니다.

해설 (17)

도움이 되나요?

//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 );
해설 (12)

39 의 다음과 같은 단순한 it&

var dir = AppDomain.CurrentDomain.BaseDirectory;
해설 (9)

S # 39 라고 하지만, 조금 덜 John& 같은 세부 확장명은 메서드입니다.

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

이제 할 수 있다.

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

또는 원할 경우:

var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();
해설 (3)

Unc 가져다줄래요 협력했습니다 유일한 솔루션으로 사용할 때 코드 및 네트워크 공유별로 없었다.

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

또한 일반 uri 를 함께 사용할 수 없다.

해설 (6)

어셈블리가 _섀도 복사_되지 않는 한 이 방법은 작동합니다:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location
해설 (0)

이건 뭐야.

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
해설 (0)
AppDomain.CurrentDomain.BaseDirectory

수행됨 기유니스 GUI.

해설 (2)

실제 문제를 테스트 하는 의심이 슬라이드에서는 해당 어셈블리에 다른 위치로 복사 현상이 있다. # 39 의 무리라구 there& 말할 수 없지만 아마도 조립품을 런타임 시에 있는 복제되었습니다 가져오기에서 뒤집기를 떠날려하면 전환하십시오 테스트 및 복제하지 않는 곳에서 조립품을 선수였다 실행하십시오 redhat. 태양으로하여 디렉터리입니다.

스위치 등 각 테스트마다 러너, 물론이겠지 다를 것으로 보인다.

Xml 데이터를 쉽게 리소스로 내에 부품 테스트 포함 고려해 본 적이 있으십니까?

해설 (1)

지금처럼 내가 말할 수 있어, 대부분의 다른 대답을 몇 가지 문제를 가지고 있다.

올바른 방법으로 대해 이 디스크 기반 (반대로 웹-기반), 비사양 가스트 조립품을 # 39 코드베이스 's' 는 현재 실행 중인 assembly& 재산이잖아 사용할 수 있습니다.

Url 이 되돌려줍니다 ('file://'). 대신 메싱 수립하였습니다 2 와 [문자열 조작] 또는 '어니스카페다타스트링' 이 혼란을 최소화하면서 로카르파스 '재산' 을 활용하여 변환할 수 있는 '열린우리당'.

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

다음은 VB.NET 포트 존 Sibly& # 39 의 코드. 비주얼 베이직 대소문자를 구분하지 않습니다 몇 가지 유형 이름 때문에 그의 변수 이름을 충돌하고 있었다.

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
해설 (1)
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var assemblyPath = assembly.GetFiles()[0].Name;
var assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);
해설 (0)

이건 어때.

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

그럼 그냥 어떤 해킹 오프하도록 필요는 없습니다.

해설 (0)

그 동안, 사실상 모든 아니예 언급한 이 번호요. I learned from the 속임수 뛰어난 [아프로바우티스타스 프로젝트] (https://github.com/approvals/ApprovalTests.Net/blob/master/ApprovalUtilities/Utilities/PathUtilities.cs). 이 기법을 사용하는 디버깅 정보를 찾을 수 있는 것은 기존 조립품을 디렉터리입니다.

  • 해당 안 됨, disk_b_s10database 최적화 모드, disk_b_s10database 작업하십시오 릴리스에는 함께 한 컴퓨터에서 다른 it 컴파일했습니다 on.* 활성화됨

하지만 이를 수 있는 경로를 통해 이를 소스 코드 파일이 상대적인 위치로 전화하시기

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;
    }
}
해설 (0)

현재 회원님이 있는 디렉터리입니다.

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

빌드와 함께 .xml 파일을 복사하면 찾을 수 있습니다.

또는

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

// The location of the Assembly
assembly.Location;
해설 (3)

39, ve been i& 아서 블리스고데바제 사용하는 대신 위치:

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("/", "\\");

39 에 노력하고 있지만, 더 이상 it& I& 100% # 39 m 있는지는 정확한. 이 페이지 http://www. http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx 다음과 같이 말합니다.

&quot, URL 이 곳에 대한 CodeBase 는 파일이 있는 반면, 위치는 경로상에서 발견었습니다 그게 사실 로드됨. 예를 들어, 조립품을 인터넷을 통해 해당 CodeBase 다운로드되었는지 &quot http://&quot 있지만, 그 위치는 &quot 함께 시작할 수 있습니다,, C:\&quot 시작할 수 있습니다. 만약 파일이 파일의 경로가 섀도 복사본 약간만이라도 위치는 복제본이므로 섀도 복사본 dir. 또한 그 사실을 알 수 있도록 설정할 수 있는 좋은 CodeBase 보장되지 않을 경우 어셈블리를 GAC. 항상 세트를 어셈블리들 디스켓에서 로드되었는지 위치, however.&quot.

대신 코드베이스 may 위치를 사용할 수 있습니다.

해설 (2)

이 모든 종류의 어플리케이션을 사용할 것이라고 생각한다.

AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory
해설 (1)

용지함 경로를 통해 얻을 수 있습니다. 아프도메인스커랑도맹자렐라티베세라크파스

해설 (0)

windows 에서 애플리케이션 (앱) 을 사용하여 '양식' 아프리카션리스트라토퍼스 됩니다

하지만 이 코드는 dll 및 콘솔 앱을 기억하기 위해 매우 어려워졌다.

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

root += slash;
string settingsIni = root + "settings.ini"
해설 (0)

그 때 모든 것을 작동합니까 개발자는 필요한 포함시키십시오 변경하십시오 코드를 변경하지 않고 있지만, 이 경우 스니핏 하고 싶었는지 코드 탐색기 프로세스가 사용할 수 있습니다.

모든 시스템에서 실행할 것이라고 나열하십시오 dll 의 프로세스 id 를 실행 중인 응용 프로그램 확인해야 할 수 있습니다, 하지만 이는 보통 너무 어렵다.

39, ve 기록되었으므로 i& 대한 자세한 내용은 어떻게 대해 이 dll δ1 II - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

해설 (2)