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>
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!