<p>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. </p>

<p>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.</p>

<p><strong>Edit</strong>: People seem to be misunderstanding what I'm asking.</p>

<p>My test library is located in say </p>

<blockquote>
  <p>C:\projects\myapplication\daotests\bin\Debug\daotests.dll</p>
</blockquote>

<p>and I would like to get this path:</p>

<blockquote>
  <p>C:\projects\myapplication\daotests\bin\Debug\</p>
</blockquote>

<p>The three suggestions so far fail me when I run from the MbUnit Gui:</p>

<ul>
<li><p><code>Environment.CurrentDirectory</code>
gives <em>c:\Program Files\MbUnit</em></p></li>
<li><p><code>System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location</code>
gives <em>C:\Documents and
Settings\george\Local
Settings\Temp\ ....\DaoTests.dll</em></p></li>
<li><p><code>System.Reflection.Assembly.GetExecutingAssembly().Location</code>
gives the same as the previous.</p></li>
</ul>

[{'answer_id': 52802, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 5, 'selected': False, 'text': '<p>This should work, unless the assembly is <em>shadow copied</em>:</p>\n\n<pre><code>string path = System.Reflection.Assembly.GetExecutingAssembly().Location\n</code></pre>\n'}, {'answer_id': 52803, 'author': 'David Basarab', 'author_id': 2469, 'author_profile': 'https://Stackoverflow.com/users/2469', 'pm_score': 2, 'selected': False, 'text': '<p>The current directory where you exist.</p>\n\n<pre><code>Environment.CurrentDirectory;  // This is the current directory of your application\n</code></pre>\n\n<p>If you copy the .xml file out with build you should find it.</p>\n\n<p>or</p>\n\n<pre><code>System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));\n\n// The location of the Assembly\nassembly.Location;\n</code></pre>\n'}, {'answer_id': 52956, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 8, 'selected': False, 'text': "<p>Does this help?</p>\n\n<pre><code>//get the full location of the assembly with DaoTests in it\nstring fullPath = System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location;\n\n//get the folder that's in\nstring theDirectory = Path.GetDirectoryName( fullPath );\n</code></pre>\n"}, {'answer_id': 52969, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 3, 'selected': False, 'text': '<pre><code>var assembly = System.Reflection.Assembly.GetExecutingAssembly();\nvar assemblyPath = assembly.GetFiles()[0].Name;\nvar assemblyDir = System.IO.Path.GetDirectoryName(assemblyPath);\n</code></pre>\n'}, {'answer_id': 52979, 'author': 'Curt Hagenlocher', 'author_id': 533, 'author_profile': 'https://Stackoverflow.com/users/533', 'pm_score': 4, 'selected': False, 'text': "<p>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.</p>\n\n<p>Such a switch is likely to be different for each test runner, of course.</p>\n\n<p>Have you considered embedding your XML data as resources inside your test assembly?</p>\n"}, {'answer_id': 52987, 'author': 'huseyint', 'author_id': 39, 'author_profile': 'https://Stackoverflow.com/users/39', 'pm_score': 4, 'selected': False, 'text': '<p>What about this:</p>\n\n<pre><code>System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n</code></pre>\n'}, {'answer_id': 52990, 'author': 'Jesse C. Slicer', 'author_id': 3312, 'author_profile': 'https://Stackoverflow.com/users/3312', 'pm_score': 1, 'selected': False, 'text': '<pre><code>string path = Path.GetDirectoryName(typeof(DaoTests).Module.FullyQualifiedName);\n</code></pre>\n'}, {'answer_id': 52996, 'author': 'dan gibson', 'author_id': 4495, 'author_profile': 'https://Stackoverflow.com/users/4495', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve been using Assembly.CodeBase instead of Location:</p>\n\n<pre><code>Assembly a;\na = Assembly.GetAssembly(typeof(DaoTests));\nstring s = a.CodeBase.ToUpper(); // file:///c:/path/name.dll\nAssert.AreEqual(true, s.StartsWith("FILE://"), "CodeBase is " + s);\ns = s.Substring(7, s.LastIndexOf(\'/\') - 7); // 7 = "file://"\nwhile (s.StartsWith("/")) {\n    s = s.Substring(1, s.Length - 1);\n}\ns = s.Replace("/", "\\\\");\n</code></pre>\n\n<p>It\'s been working, but I\'m no longer sure it is 100% correct. The page at <a href="http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx" rel="noreferrer">http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx</a> says:</p>\n\n<p><em>"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.\nIt’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.</em>"</p>\n\n<p>You <em>may</em> want to use CodeBase instead of Location.</p>\n'}, {'answer_id': 283917, 'author': 'John Sibly', 'author_id': 1078, 'author_profile': 'https://Stackoverflow.com/users/1078', 'pm_score': 11, 'selected': True, 'text': '<p><strong>Note</strong>: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0</a></p>\n<p><strong>Original answer:</strong></p>\n<p>I\'ve defined the following property as we use this often in unit testing.</p>\n<pre><code>public static string AssemblyDirectory\n{\n    get\n    {\n        string codeBase = Assembly.GetExecutingAssembly().CodeBase;\n        UriBuilder uri = new UriBuilder(codeBase);\n        string path = Uri.UnescapeDataString(uri.Path);\n        return Path.GetDirectoryName(path);\n    }\n}\n</code></pre>\n<p>The <code>Assembly.Location</code> property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use <code>CodeBase</code> which gives you the path in URI format, then <code>UriBuild.UnescapeDataString</code> removes the <code>File://</code> at the beginning, and <code>GetDirectoryName</code> changes it to the normal windows format.</p>\n'}, {'answer_id': 884444, 'author': 'Mike Schall', 'author_id': 4231, 'author_profile': 'https://Stackoverflow.com/users/4231', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n\n<pre><code>Public Shared ReadOnly Property AssemblyDirectory() As String\n    Get\n        Dim codeBase As String = Assembly.GetExecutingAssembly().CodeBase\n        Dim uriBuilder As New UriBuilder(codeBase)\n        Dim assemblyPath As String = Uri.UnescapeDataString(uriBuilder.Path)\n        Return Path.GetDirectoryName(assemblyPath)\n    End Get\nEnd Property\n</code></pre>\n"}, {'answer_id': 2567233, 'author': 'Sneal', 'author_id': 82906, 'author_profile': 'https://Stackoverflow.com/users/82906', 'pm_score': 6, 'selected': False, 'text': "<p>Same as John's answer, but a slightly less verbose extension method.</p>\n\n<pre><code>public static string GetDirectoryPath(this Assembly assembly)\n{\n    string filePath = new Uri(assembly.CodeBase).LocalPath;\n    return Path.GetDirectoryName(filePath);            \n}\n</code></pre>\n\n<p>Now you can do:</p>\n\n<pre><code>var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();\n</code></pre>\n\n<p>or if you prefer:</p>\n\n<pre><code>var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();\n</code></pre>\n"}, {'answer_id': 2887537, 'author': 'Jalal El-Shaer', 'author_id': 95380, 'author_profile': 'https://Stackoverflow.com/users/95380', 'pm_score': 8, 'selected': False, 'text': "<p>It's as simple as this:</p>\n\n<pre><code>var dir = AppDomain.CurrentDomain.BaseDirectory;\n</code></pre>\n"}, {'answer_id': 3051585, 'author': 'user368021', 'author_id': 368021, 'author_profile': 'https://Stackoverflow.com/users/368021', 'pm_score': 4, 'selected': False, 'text': '<pre><code>AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n\n<p>works with MbUnit GUI.</p>\n'}, {'answer_id': 8594253, 'author': 'rcooley56', 'author_id': 1110393, 'author_profile': 'https://Stackoverflow.com/users/1110393', 'pm_score': -1, 'selected': False, 'text': '<p>I use this to get the path to the Bin Directory:</p>\n\n<pre><code>var i = Environment.CurrentDirectory.LastIndexOf(@"\\");\nvar path = Environment.CurrentDirectory.Substring(0,i); \n</code></pre>\n\n<p>You get this result:</p>\n\n<blockquote>\n  <p>"c:\\users\\ricooley\\documents\\visual studio\n  2010\\Projects\\Windows_Test_Project\\Windows_Test_Project\\bin"</p>\n</blockquote>\n'}, {'answer_id': 9737418, 'author': 'Ignacio Soler Garcia', 'author_id': 166452, 'author_profile': 'https://Stackoverflow.com/users/166452', 'pm_score': 6, 'selected': False, 'text': '<p>The only solution that worked for me when using CodeBase and UNC Network shares was:</p>\n\n<pre><code>System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);\n</code></pre>\n\n<p>It also works with normal URIs too.</p>\n'}, {'answer_id': 17060539, 'author': 'mmmmmm', 'author_id': 767464, 'author_profile': 'https://Stackoverflow.com/users/767464', 'pm_score': 0, 'selected': False, 'text': '<p>This should work:</p>\n\n<pre><code>ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();\nAssembly asm = Assembly.GetCallingAssembly();\nString path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);\n\nstring strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");\n</code></pre>\n\n<p>I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).</p>\n'}, {'answer_id': 17440241, 'author': 'Valamas', 'author_id': 511438, 'author_profile': 'https://Stackoverflow.com/users/511438', 'pm_score': 0, 'selected': False, 'text': '<p>This is what I came up with. <strong>In between web projects, unit tests (nunit and resharper test runner)</strong>; I found this worked for me.</p>\n\n<p>I have been looking for code to detect what configuration the build is in, <code>Debug/Release/CustomName</code>. Alas, the <code>#if DEBUG</code>. <em>So if someone can improve that</em>!</p>\n\n<p>Feel free to edit and improve.</p>\n\n<p><strong>Getting app folder</strong>. Useful for web roots, unittests to get the folder of test files.</p>\n\n<pre><code>public static string AppPath\n{\n    get\n    {\n        DirectoryInfo appPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);\n\n        while (appPath.FullName.Contains(@"\\bin\\", StringComparison.CurrentCultureIgnoreCase)\n                || appPath.FullName.EndsWith(@"\\bin", StringComparison.CurrentCultureIgnoreCase))\n        {\n            appPath = appPath.Parent;\n        }\n        return appPath.FullName;\n    }\n}\n</code></pre>\n\n<p><strong>Getting bin folder</strong>: Useful for executing assemblies using reflection. If files are copied there due to build properties. </p>\n\n<pre><code>public static string BinPath\n{\n    get\n    {\n        string binPath = AppDomain.CurrentDomain.BaseDirectory;\n\n        if (!binPath.Contains(@"\\bin\\", StringComparison.CurrentCultureIgnoreCase)\n            &amp;&amp; !binPath.EndsWith(@"\\bin", StringComparison.CurrentCultureIgnoreCase))\n        {\n            binPath = Path.Combine(binPath, "bin");\n            //-- Please improve this if there is a better way\n            //-- Also note that apps like webapps do not have a debug or release folder. So we would just return bin.\n#if DEBUG\n            if (Directory.Exists(Path.Combine(binPath, "Debug"))) \n                        binPath = Path.Combine(binPath, "Debug");\n#else\n            if (Directory.Exists(Path.Combine(binPath, "Release"))) \n                        binPath = Path.Combine(binPath, "Release");\n#endif\n        }\n            return binPath;\n    }\n}\n</code></pre>\n'}, {'answer_id': 24249706, 'author': 'spender', 'author_id': 14357, 'author_profile': 'https://Stackoverflow.com/users/14357', 'pm_score': 3, 'selected': False, 'text': '<p>As far as I can tell, most of the other answers have a few problems.</p>\n\n<p>The correct way to do this for a <a href="http://blogs.msdn.com/b/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx" rel="nofollow noreferrer">disk-based (as opposed to web-based), non-GACed assembly</a> is to use the currently executing assembly\'s <code>CodeBase</code> property.</p>\n\n<p>This returns a URL (<code>file://</code>). Instead of messing around with <a href="https://stackoverflow.com/a/52996/14357">string manipulation</a> or <a href="https://stackoverflow.com/a/283917/14357"><code>UnescapeDataString</code></a>, this can be converted with minimal fuss by leveraging the <code>LocalPath</code> property of <code>Uri</code>. </p>\n\n<pre><code>var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;\nvar filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;\nvar directoryPath = Path.GetDirectoryName(filePathToCodeBase);\n</code></pre>\n'}, {'answer_id': 24283320, 'author': 'user2009677', 'author_id': 2009677, 'author_profile': 'https://Stackoverflow.com/users/2009677', 'pm_score': -1, 'selected': False, 'text': '<p>Web application?</p>\n\n<pre><code>Server.MapPath("~/MyDir/MyFile.ext")\n</code></pre>\n'}, {'answer_id': 32738924, 'author': 'Tez Wingfield', 'author_id': 3305976, 'author_profile': 'https://Stackoverflow.com/users/3305976', 'pm_score': 0, 'selected': False, 'text': '<p>I find my solution adequate for the retrieval of the location.</p>\n\n<pre><code>var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;\n</code></pre>\n'}, {'answer_id': 32863106, 'author': 'Andrey Bushman', 'author_id': 1306132, 'author_profile': 'https://Stackoverflow.com/users/1306132', 'pm_score': 0, 'selected': False, 'text': '<p>I got the same behaviour in the <code>NUnit</code> in the past. By default <code>NUnit</code> copies your assembly into the temp directory. You can change this behaviour in the <code>NUnit</code> settings:</p>\n\n<p><a href="https://i.stack.imgur.com/VxmI7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VxmI7.png" alt="enter image description here"></a></p>\n\n<p>Maybe <code>TestDriven.NET</code> and <code>MbUnit</code> GUI have the same settings.</p>\n'}, {'answer_id': 32870042, 'author': 'George Mauer', 'author_id': 5056, 'author_profile': 'https://Stackoverflow.com/users/5056', 'pm_score': 3, 'selected': False, 'text': '<p>In all these years, nobody has actually mentioned this one. A trick I learned from the awesome <a href="https://github.com/approvals/ApprovalTests.Net/blob/master/ApprovalUtilities/Utilities/PathUtilities.cs" rel="noreferrer">ApprovalTests project</a>. The trick is that you use the debugging information in the assembly to find the original directory.</p>\n\n<p><strong>This will not work in RELEASE mode, nor with optimizations enabled, nor on a machine different from the one it was compiled on.</strong></p>\n\n<p>But this will get you paths that are <strong>relative to the location of the source code file you call it from</strong></p>\n\n<pre><code>public static class PathUtilities\n{\n    public static string GetAdjacentFile(string relativePath)\n    {\n        return GetDirectoryForCaller(1) + relativePath;\n    }\n    public static string GetDirectoryForCaller()\n    {\n        return GetDirectoryForCaller(1);\n    }\n\n\n    public static string GetDirectoryForCaller(int callerStackDepth)\n    {\n        var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);\n        return GetDirectoryForStackFrame(stackFrame);\n    }\n\n    public static string GetDirectoryForStackFrame(StackFrame stackFrame)\n    {\n        return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;\n    }\n}\n</code></pre>\n'}, {'answer_id': 36794977, 'author': 'sumitup', 'author_id': 1390728, 'author_profile': 'https://Stackoverflow.com/users/1390728', 'pm_score': 2, 'selected': False, 'text': '<p>You can get the bin path by\n    AppDomain.CurrentDomain.RelativeSearchPath</p>\n'}, {'answer_id': 39216220, 'author': 'David C Fuchs', 'author_id': 5719295, 'author_profile': 'https://Stackoverflow.com/users/5719295', 'pm_score': 3, 'selected': False, 'text': '<p>How about this ...  </p>\n\n<pre><code>string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n</code></pre>\n\n<p>Then just hack off what you do not need</p>\n'}, {'answer_id': 39549085, 'author': 'Bryan', 'author_id': 313072, 'author_profile': 'https://Stackoverflow.com/users/313072', 'pm_score': 2, 'selected': False, 'text': '<p>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. </p>\n\n<p>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. </p>\n\n<p>I\'ve written a full description of how do this for a dll inside II - <a href="http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/" rel="nofollow">http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/</a></p>\n'}, {'answer_id': 47760173, 'author': 'gamesguru', 'author_id': 8555624, 'author_profile': 'https://Stackoverflow.com/users/8555624', 'pm_score': 2, 'selected': False, 'text': '<p>in a windows form app, you can simply use <code>Application.StartupPath</code></p>\n\n<p>but for DLLs and console apps the code is much harder to remember...</p>\n\n<pre><code>string slash = Path.DirectorySeparatorChar.ToString();\nstring root = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n\nroot += slash;\nstring settingsIni = root + "settings.ini"\n</code></pre>\n'}, {'answer_id': 53048485, 'author': 'Fedor Shihantsov', 'author_id': 1518180, 'author_profile': 'https://Stackoverflow.com/users/1518180', 'pm_score': 2, 'selected': False, 'text': '<p>You will get incorrect directory if a path contains the \'#\' symbol.\nSo I use a modification of the John Sibly answer that is combination UriBuilder.Path and UriBuilder.Fragment:</p>\n\n<pre><code>public static string AssemblyDirectory\n{\n    get\n    {\n        string codeBase = Assembly.GetExecutingAssembly().CodeBase;\n        UriBuilder uri = new UriBuilder(codeBase);\n        //modification of the John Sibly answer    \n        string path = Uri.UnescapeDataString(uri.Path.Replace("/", "\\\\") + \n          uri.Fragment.Replace("/", "\\\\"));\n        return Path.GetDirectoryName(path);\n     }\n}\n</code></pre>\n'}, {'answer_id': 58051383, 'author': 'Ilya Chernomordik', 'author_id': 1671558, 'author_profile': 'https://Stackoverflow.com/users/1671558', 'pm_score': 5, 'selected': False, 'text': '<p>I believe this would work for any kind of application:</p>\n\n<pre><code>AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n'}, {'answer_id': 62626131, 'author': 'cube45', 'author_id': 2663813, 'author_profile': 'https://Stackoverflow.com/users/2663813', 'pm_score': 4, 'selected': False, 'text': '<p>Starting with .net framework 4.6 / .net core 1.0, there is now a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.appcontext.basedirectory" rel="noreferrer">AppContext.BaseDirectory</a>, which should give the same result as <code>AppDomain.CurrentDomain.BaseDirectory</code>, except that AppDomains were not part of the .net core 1.x /.net standard 1.x API.</p>\n<pre class="lang-cs prettyprint-override"><code>AppContext.BaseDirectory\n</code></pre>\n<p>EDIT: The documentation now even state:</p>\n<blockquote>\n<p>In .NET 5.0 and later versions, for bundled assemblies, the value returned is the containing directory of the host executable.</p>\n</blockquote>\n<p>Indeed, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location?view=net-5.0" rel="noreferrer">Assembly.Location doc</a> doc says :</p>\n<blockquote>\n<p>In .NET 5.0 and later versions, for bundled assemblies, the value returned is an empty string.</p>\n</blockquote>\n'}, {'answer_id': 63626644, 'author': 'TPG', 'author_id': 2463156, 'author_profile': 'https://Stackoverflow.com/users/2463156', 'pm_score': 2, 'selected': False, 'text': '<p>For ASP.Net, it doesn\'t work. I found a better covered solution at <a href="https://stackoverflow.com/questions/8669833/why-appdomain-currentdomain-basedirectory-not-contains-bin-in-asp-net-app">Why AppDomain.CurrentDomain.BaseDirectory not contains &quot;bin&quot; in asp.net app?</a>. It works for both Win Application and ASP.Net Web Application.</p>\n<pre><code>public string ApplicationPath\n    {\n        get\n        {\n            if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))\n            {\n                return AppDomain.CurrentDomain.BaseDirectory; //exe folder for WinForms, Consoles, Windows Services\n            }\n            else\n            {\n                return AppDomain.CurrentDomain.RelativeSearchPath; //bin folder for Web Apps \n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 68223295, 'author': 'Bennik2000', 'author_id': 4563449, 'author_profile': 'https://Stackoverflow.com/users/4563449', 'pm_score': 3, 'selected': False, 'text': '<h2>tl;dr</h2>\n<p>The concept of an assembly and a DLL file are not the same. Depending on how the assembly was loaded the path information gets lost or is <strong>not available at all</strong>.\nMost of the time the provided answers will work, though.</p>\n<hr />\n<p>There is one misconception the question and the previous answers have. In most of the cases the provided answers will work just fine but\nthere are cases where it is <strong>not possible</strong> to get the correct path of the assembly which the current code resides.</p>\n<p>The concept of an assembly - which contains executable code - and a dll file - which contains the assembly - are not tightly coupled. An assembly may\ncome from a DLL file but it does not have to.</p>\n<p>Using the <code>Assembly.Load(Byte[])</code> (<a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.load?view=netframework-4.7.2" rel="noreferrer">MSDN</a>) method you can load an assembly directly from a byte array in memory.\nIt does not matter where the byte array comes from. It could be loaded from a file, downloaded from the internet, dynamically generated,...</p>\n<p>Here is an example which loads an assembly from a byte array. The path information gets lost after the file was loaded. It is not possible to\nget the original file path and all previous described methods do not work.</p>\n<p>This method is located in the executing assembly which is located at &quot;D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe&quot;</p>\n<pre><code>static void Main(string[] args)\n{\n    var fileContent = File.ReadAllBytes(@&quot;C:\\Library.dll&quot;);\n\n    var assembly = Assembly.Load(fileContent);\n\n    // Call the method of the library using reflection\n    assembly\n        ?.GetType(&quot;Library.LibraryClass&quot;)\n        ?.GetMethod(&quot;PrintPath&quot;, BindingFlags.Public | BindingFlags.Static)\n        ?.Invoke(null, null);\n\n    Console.WriteLine(&quot;Hello from Application:&quot;);\n    Console.WriteLine($&quot;GetViaAssemblyCodeBase: {GetViaAssemblyCodeBase(assembly)}&quot;);\n    Console.WriteLine($&quot;GetViaAssemblyLocation: {assembly.Location}&quot;);\n    Console.WriteLine($&quot;GetViaAppDomain       : {AppDomain.CurrentDomain.BaseDirectory}&quot;);\n\n    Console.ReadLine();\n}\n</code></pre>\n<p>This class is located in the Library.dll:</p>\n<pre><code>public class LibraryClass\n{\n    public static void PrintPath()\n    {\n        var assembly = Assembly.GetAssembly(typeof(LibraryClass));\n        Console.WriteLine(&quot;Hello from Library:&quot;);\n        Console.WriteLine($&quot;GetViaAssemblyCodeBase: {GetViaAssemblyCodeBase(assembly)}&quot;);\n        Console.WriteLine($&quot;GetViaAssemblyLocation: {assembly.Location}&quot;);\n        Console.WriteLine($&quot;GetViaAppDomain       : {AppDomain.CurrentDomain.BaseDirectory}&quot;);\n    }\n}\n\n</code></pre>\n<p>For the sake of completeness here is the implementations of <code>GetViaAssemblyCodeBase()</code> which is the same for both assemblies:</p>\n<pre><code>private static string GetViaAssemblyCodeBase(Assembly assembly)\n{\n    var codeBase = assembly.CodeBase;\n    var uri = new UriBuilder(codeBase);\n    return Uri.UnescapeDataString(uri.Path);\n}\n\n</code></pre>\n<p>The Runner prints the following output:</p>\n<pre><code>Hello from Library:\nGetViaAssemblyCodeBase: D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe\nGetViaAssemblyLocation:\nGetViaAppDomain       : D:\\Software\\DynamicAssemblyLoad\\DynamicAssemblyLoad\\bin\\Debug\\\nHello from Application:\nGetViaAssemblyCodeBase: D:/Software/DynamicAssemblyLoad/DynamicAssemblyLoad/bin/Debug/Runner.exe\nGetViaAssemblyLocation:\nGetViaAppDomain       : D:\\Software\\DynamicAssemblyLoad\\DynamicAssemblyLoad\\bin\\Debug\\\n</code></pre>\n<p>As you can see, neither the code base, location or base directory are correct.</p>\n'}]
['https://Stackoverflow.com/questions/52797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/']