C#中如何获取解决方案/.csproj路径而非Debug文件夹路径?
获取与.csproj同级的目录路径的最优方案
以下是几种无需硬编码向上导航目录的可靠方案:
方案1:通过MSBuild属性注入项目目录到程序集元数据
在你的.csproj文件中添加以下配置,将项目目录路径嵌入到程序集的元数据中,之后在代码里读取该元数据即可:
<PropertyGroup> <!-- 注入项目目录到程序集元数据 --> <AssemblyMetadata Include="ProjectDirectory" Value="$(ProjectDir)" /> </PropertyGroup>
然后在C#代码中读取这个元数据:
using System.Reflection; using System.Linq; var assembly = Assembly.GetExecutingAssembly(); var projectDirAttr = assembly.GetCustomAttributes<AssemblyMetadataAttribute>() .FirstOrDefault(a => a.Key == "ProjectDirectory"); if (projectDirAttr != null) { string projectDirectory = projectDirAttr.Value; // 此处的projectDirectory即为与.csproj同级的目录路径 }
方案2:通过构建时替换配置文件变量
在appsettings.json(或其他配置文件)中添加占位项:
{ "Paths": { "ProjectRoot": "$(ProjectDir)" } }
然后在.csproj文件中配置构建时替换变量,并确保配置文件正确复制到输出目录:
<ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <TransformOnBuild>true</TransformOnBuild> </None> </ItemGroup> <PropertyGroup> <TransformOnBuild>true</TransformOnBuild> <TransformOutOfDateOnly>true</TransformOutOfDateOnly> </PropertyGroup>
之后在代码中读取配置即可获取项目目录:
using Microsoft.Extensions.Configuration; var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); string projectDirectory = config["Paths:ProjectRoot"];
方案3:自动查找.csproj文件所在目录
如果不想依赖构建配置,可以通过遍历目录查找当前项目的.csproj文件,这种方法比固定向上跳多级更鲁棒(适配目录结构变化):
using System.IO; using System.Reflection; using System.Linq; string currentAssemblyPath = Assembly.GetExecutingAssembly().Location; string currentDir = Path.GetDirectoryName(currentAssemblyPath); string projectDirectory = null; // 向上遍历目录,直到找到包含.csproj文件的目录 while (currentDir != null) { if (Directory.EnumerateFiles(currentDir, "*.csproj").Any()) { projectDirectory = currentDir; break; } currentDir = Directory.GetParent(currentDir)?.FullName; } // 找到后即可使用projectDirectory变量
内容的提问来源于stack exchange,提问作者Lars
相关产品推荐
相关产品推荐

