在域中运行的单元测试中获取物理文件路径,而不是域的相对路径

本文关键字:路径 相对 单元测试 运行 获取 文件 | 更新日期: 2023-09-27 17:59:41

如何在单元测试中获得物理文件而不是与域相关的路径?

我使用的是这个代码:

 var codebase = Assembly.GetExecutingAssembly().CodeBase;
 var pathUrlToDllDirectory = Path.GetDirectoryName(codebase);
 var pathToDllDirectory = new Uri(pathUrlToDllDirectory).LocalPath;

我得到的是这个

file:''compdata''folders$''userA''Documents''Projects''ProjectA''ProjectA.Test''bin''Debug

但我所期望的是这样的事情:

C:'windows'userA'Documents'Projects'ProjectA'ProjectA.Test'bin'Debug

在域中运行的单元测试中获取物理文件路径,而不是域的相对路径

我为Assembly创建了这些扩展以获得这些扩展。看看它是否适合你:

using System.IO;
using System.Reflection;

public static class AssemblyExtensions
{
    /// <summary>
    /// Implemented - Returns the full path of the assembly file.
    /// </summary>
    public static string GetAssemblyPath(this Assembly Assemb)
    {
        string FileName = Assemb.CodeBase;
        if (FileName.Substring(0, 4).ToUpperInvariant() == "FILE")
            FileName = FileName.Remove(0, 8);
        return FileName;
    }

    /// <summary>
    /// Implemented - Returns the path to the folder where the assembly file is located
    /// </summary>
    public static string GetAssemblyFolder(this Assembly Assemb)
    {
        return Path.GetDirectoryName(GetAssemblyPath(Assemb));
    }

    /// <summary>
    /// Implemented - Combines the assembly folder with the passed filename, returning the full path of that file in the assmebly's folder.
    /// </summary>
    public static string GetFileInAssemblyFolder(this Assembly Assemb, string FileName)
    {
        return Path.Combine(GetAssemblyFolder(Assemb), FileName);
    }

    /// <summary>
    /// Implemented - Returns the full name of the embedded resources containing the passed string - Match case
    /// </summary>
    /// <param name="Assemb"></param>
    /// <param name="ResourceName"></param>
    /// <returns></returns>
    public static IEnumerable<string> GetResourcesContainingString(this Assembly Assemb, string ResourceName)
    {
        return Assemb.GetManifestResourceNames().Where(S => S.Contains(ResourceName));
    }

    /// <summary>
    /// Implemented - Returns the full name of the first embedded resource containing the passed string - Match case
    /// </summary>
    /// <param name="Assemb"></param>
    /// <param name="ResourceName"></param>
    /// <returns></returns>
    public static string GetFirstResourceContainingString(this Assembly Assemb, string ResourceName)
    {
        return Assemb.GetResourcesContainingString(ResourceName).First();
    }
}