与 .slnFile 相关的问题
本文关键字:问题 slnFile | 更新日期: 2023-09-27 18:33:33
问题 1:C# 项目文本的默认解决方案文件的格式是否始终相同?
Project(Solution GUI) = SolutionName , ProjectPath, csProjPath, ProjectGUI
例如:
Project("{FAE14EC0-321D-12D3-GF35-01C04F79EFBC}") = "WindowsFormsApplication26", "WindowsFormsApplication26'WindowsFormsApplication26.csproj", "{25F0453B-9C88-4C9E-AG6A-97873BB6EA23}"
EndProject
与以下格式相同:第一个它将具有解决方案 GUI,然后是解决方案名称,然后是 csproj 路径然后项目图形用户界面
问题2:我创建了一个正则表达式来获取.sln生成的文本,这就是我得到的:
Regex projectRegex = new Regex(@"Project'('""([^'""]+)'""')'s*'='s*'""([^'""]+)'""','s*'""([^'""]+)""','s*'""([^'""]+)""");
但我不确定我的正则表达式中是否存在与第一个问题相关的错误,所以我在想是否有更好的正则表达式或任何条件(例如解析或任何必须更快)来获取 ProjectText 具体(我需要得到的)是 csProj 路径(在上面的 Group3 上的正则表达式模式上)
对于Q1所示的示例应用的组:
Group1: {FAE14EC0-321D-12D3-GF35-01C04F79EFBC}
Group2: WindowsFormsApplication26
Group3: WindowsFormsApplication26'WindowsFormsApplication26.csproj
Group4: {25F0453B-9C88-4C9E-AG6A-97873BB6EA23}
我认为您的方式应该正常工作,但是为了从解决方案文件中提取信息,我们通过访问"Microsoft.Build"命名空间的内部技术使用以下方法。由于相应的框架函数被标记为internal
,因此有必要"破解"它们。因此使用反射的复杂方式。(这是我们在互联网上找到的其他代码片段的浓缩摘录 - 也在SO中)
public struct ProjectData
{
public string Name;
public string Guid;
public string Path;
}
public static List<ProjectData> GetProjectsInSolution(string pathToSolutionFile)
{
Type parserType = Type.GetType("Microsoft.Build.Construction.SolutionParser, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false, false);
ConstructorInfo constructorInfo = parserType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First();
object solutionParser = constructorInfo.Invoke(null);
PropertyInfo solutionFileProperty = parserType.GetProperty("SolutionFile", BindingFlags.NonPublic | BindingFlags.Instance);
solutionFileProperty.SetValue(solutionParser, pathToSolutionFile);
MethodInfo parserMethod = parserType.GetMethod("ParseSolutionFile", BindingFlags.NonPublic | BindingFlags.Instance);
parserMethod.Invoke(solutionParser, null);
PropertyInfo projectInfo = parserType.GetProperty("Projects", BindingFlags.NonPublic | BindingFlags.Instance);
object[] projects = projectInfo.GetValue(solutionParser) as object[];
Type projectType = Type.GetType("Microsoft.Build.Construction.ProjectInSolution, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false, false);
PropertyInfo nameInfo = projectType.GetProperty("ProjectName", BindingFlags.NonPublic | BindingFlags.Instance);
PropertyInfo guidInfo = projectType.GetProperty("ProjectGuid", BindingFlags.NonPublic | BindingFlags.Instance);
PropertyInfo pathInfo = projectType.GetProperty("RelativePath", BindingFlags.NonPublic | BindingFlags.Instance);
List<ProjectData> projectData = new List<ProjectData>();
if (projects != null)
{
foreach (object project in projects)
{
projectData.Add(new ProjectData()
{
Name = nameInfo.GetValue(project) as string,
Guid = guidInfo.GetValue(project) as string,
Path = pathInfo.GetValue(project) as string
});
}
}
return projectData;
}