You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码在Solution Explorer已有文件夹下嵌套新文件夹?

如何通过DTE将文件夹嵌套添加到Visual Studio项目的已有文件夹下

你的问题出在直接调用project.ProjectItems.AddFromDirectory,这个方法默认是把文件夹添加到项目根目录,不会自动识别本地路径的层级嵌套。要实现把TEST文件夹挂到src下面,得先找到src对应的ProjectItem对象,再在它的子项集合里调用AddFromDirectory。

解决步骤:

  • 第一步:遍历项目的ProjectItems,找到目标父文件夹(比如src)的ProjectItem,注意要筛选出物理文件夹类型(Kind == vsProjectItemKindPhysicalFolder)
  • 第二步:创建本地文件夹后,调用父文件夹ProjectItem的ProjectItems.AddFromDirectory方法

修改后的完整代码:

using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using EnvDTE;

// ... 你的其他代码

string pathx = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"../../App.config");

// 获取当前Visual Studio实例
DTE dte = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
Solution solution = dte.Solution;
Project project = solution.Projects.Item(1); // 根据实际项目索引或名称修改

string parentFolder = Directory.GetParent(Assembly.GetEntryAssembly().Location).Parent.Parent.FullName;
string concatFolder = @"src\TEST";
string localFolder = Path.Combine(parentFolder, concatFolder);

if (!Directory.Exists(localFolder))
{
    try
    {
        Directory.CreateDirectory(localFolder);
        
        // 1. 找到src文件夹对应的ProjectItem
        ProjectItem srcFolderItem = null;
        foreach (ProjectItem item in project.ProjectItems)
        {
            // 确认是物理文件夹且名称匹配
            if (item.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder && item.Name.Equals("src", StringComparison.OrdinalIgnoreCase))
            {
                srcFolderItem = item;
                break;
            }
        }

        if (srcFolderItem != null)
        {
            // 2. 在src文件夹下添加TEST目录
            srcFolderItem.ProjectItems.AddFromDirectory(localFolder);
        }
        else
        {
            MessageBox.Show("未找到src文件夹");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

额外说明:

  • 如果你的src文件夹本身是嵌套在其他文件夹下的,可以递归遍历ProjectItems来定位它
  • 确保项目已引用EnvDTE程序集,否则无法识别vsProjectItemKindPhysicalFolder常量

内容的提问来源于stack exchange,提问作者Zenek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:58:28