Home > Backend Development > C++ > How Can I Reliably Find the Directory Path of My C# Assembly?

How Can I Reliably Find the Directory Path of My C# Assembly?

Linda Hamilton
Release: 2025-01-31 22:51:16
Original
822 people have browsed it

How Can I Reliably Find the Directory Path of My C# Assembly?

Get the assembly path in C#

In the unit test, the path of the current execution code is often required to locate the relevant resources, such as XML files.

Directly using is not always reliable, because it usually points to the path of the test framework, not the assembly of the test. Similarly, the unexpected temporary path may be returned in some test tools.

In order to solve this problem, the Environment.CurrentDirectory attribute can be used to obtain the URI of the execution assembly. Through , you can extract the unscoded file path from this URI. Finally, use Assembly.GetExecutingAssembly().Location to obtain the directory path of the assembly.

The following code fragment defines an auxiliary attribute to provide the assembly setting directory path: Assembly.CodeBase UriBuilder Path.GetDirectoryName In the test code, just access this attribute:

This method proves that it is reliable in the test scenario of various units using NUNIT and Mbunit to ensure that the correct assembly path can always be retrieved.
<code class="language-csharp">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);
    }
}</code>
Copy after login

The above is the detailed content of How Can I Reliably Find the Directory Path of My C# Assembly?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template