有没有简单的方法可以将多个项目添加到解决方案?

时间:2019-04-19 16:11:24

标签: c# visual-studio solution sln-file

在某些解决方案中,我在开发过程中使用对内部项目的直接引用,并切换到nuget引用进行发布。但是,手动将30多个项目添加到新解决方案中是一项繁琐的任务。

我想知道是否有更快的方法来做到这一点。对于项目,这很容易,因为您只需复制/粘贴xml,但是解决方案文件不那么容易编辑,但是也许有一些窍门?

1 个答案:

答案 0 :(得分:0)

我已经基于@JamesFaix链接对visualstudio的可扩展性做了一些重新研究,并设法将这小段代码放在一起:

using System;
using System.IO;
using System.Linq;
using EnvDTE;
using EnvDTE80;

class Program
{
    static void Main(string[] args)
    {
        // VS2019
        var dteType = Type.GetTypeFromProgID("VisualStudio.DTE.16.0", true);
        var dte = (EnvDTE.DTE)System.Activator.CreateInstance(dteType);

        var sln = (SolutionClass)dte.Solution;

        // Solution to add projects to
        sln.Open(@"C:\Projects\MyProject\MySolution.sln");

        // Projects should be added to the "lib" solution-folder.
        var lib = FindSolutionFolderOrCreate(sln, "lib");

        // These projects should be added.
        var projectPaths = new[]
        {
            @"C:\Projects\MyLibs\Lib1.csproj",
            @"C:\Projects\MyLibs\Lib2.csproj"
        };

        foreach (var path in projectPaths)
        {
            var name = Path.GetFileNameWithoutExtension(path);
            // If project not already in the solution-folder then add it.
            if(!(lib.Parent.ProjectItems.Cast<ProjectItem>().Any(pi => pi.Name == name)))
            {
                lib.AddFromFile(path);
            }
        }

        dte.Solution.Close(true);
    }

    private static SolutionFolder FindSolutionFolderOrCreate(SolutionClass sln, string folderName)
    {
        foreach (var x in sln.Projects)
        {
            if (x is Project p && p.Name.Equals(folderName, StringComparison.OrdinalIgnoreCase))
            {
                return (SolutionFolder)p.Object;
            }

        }

        var proj = (sln as Solution2).AddSolutionFolder(folderName);

        return (SolutionFolder)proj.Object;
    }
}
此实用程序的

*.csproj文件:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <!--<TargetFramework>netcoreapp2.2</TargetFramework>-->
    <TargetFramework>net47</TargetFramework>
    <EnableUnmanagedDebugging>true</EnableUnmanagedDebugging>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>full</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

  <ItemGroup>
    <Reference Include="EnvDTE">
      <HintPath>..\..\..\..\..\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies\envdte.dll</HintPath>
    </Reference>
    <Reference Include="EnvDTE80">
      <HintPath>..\..\..\..\..\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PublicAssemblies\envdte80.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

我在这里使用net47是因为netcoreapp不允许您调试COM对象,这确实使用户感到痛苦。

您还需要引用两个EnvDTE文件。