.net - 如何从一组现有项目创建解决方案文件 (.sln)?

标签 .net visual-studio

有没有办法为大量项目快速创建 .sln 文件?

向解决方案添加 200 多个项目相当乏味,我正在寻找一种遍历目录树并让我能够从不同位置一次性添加多个项目的解决方案。

我真的在寻找一个漂亮的 GUI 来实现这一点。

最佳答案

我认为没有工具可以做到这一点,但解决方案文件格式非常简单,因此您自己可以轻松完成:

static void Main()
{
    string header = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1";

    string globalSections = @"Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|Any CPU = Debug|Any CPU
        Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal";

    string csharpProjectTemplate = @"Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{0}"", ""{1}"", ""{2}""
EndProject";

    string rootPath = @"D:\MyProjects";
    string solutionName = "MySolution";
    string solutionPath = Path.Combine(rootPath, solutionName + ".sln");
    var projectFiles = Directory.GetFiles(rootPath, "*.csproj", SearchOption.AllDirectories);
    using (var stream = File.OpenWrite(solutionPath))
    using (var writer = new StreamWriter(stream))
    {
        writer.WriteLine(header);
        var xmlns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
        foreach (var projectFile in projectFiles)
        {
            string name = Path.GetFileNameWithoutExtension(projectFile);
            string relativePath = projectFile.Substring(rootPath.Length).TrimStart('\\');
            var doc = XDocument.Load(projectFile);
            var guidElement = doc.Root.Elements(xmlns + "PropertyGroup")
                                      .Elements(xmlns + "ProjectGuid")
                                      .FirstOrDefault();
            if (guidElement == null)
                continue;

            string guid = guidElement.Value;

            string entry = string.Format(csharpProjectTemplate, name, relativePath, guid);
            writer.WriteLine(entry);
        }
        writer.WriteLine(globalSections);
    }
}

(您不需要生成 ProjectConfigurationPlatforms 部分,当您打开解决方案时,Visual Studio 会自动为您创建默认的构建配置)

上面的代码仅处理C#项目;如果您有其他项目类型,您可能需要对其进行调整(您需要为每个项目类型找到适当的 GUID)。

关于.net - 如何从一组现有项目创建解决方案文件 (.sln)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294410/

相关文章:

c++ - Visual C++ 14 - 无法构建基于 Visual C++ 12 的简单线程程序

c# - 从电源查询设置时如何从 header 中删除 MaxDataServiceVersion : 3. 0

错误状态样式的 jQuery 交互提示

.net - 立即检测客户端与服务器套接字的断开连接

python - 将 django 应用程序从免费扩展到基本应用程序服务时出现运行时错误

c# - 如何使用Visual Studio 2019和C#立即添加所有缺少的用法

c# - 配置系统初始化失败

.net - 如何将 Visual Studio 安装到可移动驱动器?

c# - 找出最后一个焦点的控件

c# - 组合框 SelectedItem 未按预期工作