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

标签 c# unit-testing path

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

我正在使用这段代码:

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

我得到的是这个

文件:\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();
    }
}

关于c# - 在域中运行的单元测试中获取物理文件路径而不是域的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31058668/

相关文章:

c# - AutoMapper Custom Resolver 在构造函数中请求可选参数

c# - 如何使用 LINQ 计算最长连胜?

perl - Perl Test::More .t 文件中的范围变量

powershell修改 '.\'并调用.ps1

java - 如何获取eclipse工作空间路径

c# - NLog 有时不写入文件

java - OnPostExecute 永远不会被调用

java - 具有多个私有(private)最终字段的测试 Config 类

java - 如何使用 Junit 模拟 Builder

ruby - Ruby gems 的默认搜索路径是什么?即默认的 GEM_HOME