如何在C#/.NET中读取Visual Studio项目与解决方案位置设置
在C#/.NET中获取Visual Studio 2019的项目及模板路径
方法1:通过Visual Studio自动化模型(DTE)获取(推荐)
这种方式直接读取VS当前生效的配置,准确性最高,适合VS扩展或能获取DTE实例的场景:
using EnvDTE; using EnvDTE80; // 获取VS的DTE实例(VS扩展中可通过Package.GetGlobalService(typeof(DTE))获取) DTE2 dte = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.16.0"); // 读取项目位置 string projectLocation = dte.Properties["Environment", "Projects"].Item("Location").Value.ToString(); // 读取用户项目模板位置 string userProjectTemplatesLocation = dte.Properties["Environment", "Projects"].Item("UserProjectTemplatesLocation").Value.ToString(); // 读取用户项模板位置 string userItemTemplatesLocation = dte.Properties["Environment", "Projects"].Item("UserItemTemplatesLocation").Value.ToString();
注意:需要引用EnvDTE和EnvDTE80程序集,可通过NuGet安装Microsoft.VisualStudio.Interop包获取。
方法2:直接读取注册表
VS 2019的用户配置存储在HKEY_CURRENT_USER分支下,而非你之前查看的HKEY_LOCAL_MACHINE。路径为HKCU\Software\Microsoft\VisualStudio\16.0_<InstanceId>,其中<InstanceId>是VS的实例ID(单实例安装时仅有一个该格式的子项)。
以下是读取对应路径的C#代码:
using Microsoft.Win32; string vsBaseRegPath = @"Software\Microsoft\VisualStudio"; using (RegistryKey vsRootKey = Registry.CurrentUser.OpenSubKey(vsBaseRegPath)) { foreach (string subKeyName in vsRootKey.GetSubKeyNames()) { if (subKeyName.StartsWith("16.0_")) { using (RegistryKey projectKey = vsRootKey.OpenSubKey($@"{subKeyName}\Projects")) { if (projectKey == null) continue; string projectLoc = projectKey.GetValue("Location")?.ToString(); string userProjTemplates = projectKey.GetValue("UserProjectTemplatesLocation")?.ToString(); string userItemTemplates = projectKey.GetValue("UserItemTemplatesLocation")?.ToString(); // 输出或使用路径 Console.WriteLine($"项目位置: {projectLoc}"); Console.WriteLine($"用户项目模板位置: {userProjTemplates}"); Console.WriteLine($"用户项模板位置: {userItemTemplates}"); } } } }
如果存在多个VS 2019实例,可通过读取子项中的SKUEdition值(如Community/Professional/Enterprise)筛选目标实例。
内容的提问来源于stack exchange,提问作者Gauthier
相关产品推荐
相关产品推荐

