c# - 如何从 Visual Studio Package 项目获取当前解决方案名称?

标签 c# visual-studio vsix solution envdte

我创建了一个 Visual Studio 包项目,其中包含一个自定义菜单,我想将其添加到 Visual Studio (2013)。

我正在尝试在运行时获取当前的解决方案名称/目录。

我尝试过这个解决方案:

DTE dte = (DTE)GetService(typeof(DTE));
string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);

但是dte.Solution.FullName始终为空。

我虽然这与我在 Debug模式下运行并且为此目的创建了一个新的 Visual Studio 实例有关,但当我安装扩展并在运行时从 Visual Studio 运行它时也会发生这种情况任何菜单。

我缺少什么想法吗?

谢谢

附注我使用的解决方案取自这里:
How do you get the current solution directory from a VSPackage?

最佳答案

您可以通过从执行程序集的目录树中查找 .sln 文件来实现此目的:

public static class FileUtils
{
    public static string GetAssemblyFileName() => GetAssemblyPath().Split(@"\").Last();
    public static string GetAssemblyDir() => Path.GetDirectoryName(GetAssemblyPath());
    public static string GetAssemblyPath() => Assembly.GetExecutingAssembly().Location;
    public static string GetSolutionFileName() => GetSolutionPath().Split(@"\").Last();
    public static string GetSolutionDir() => Directory.GetParent(GetSolutionPath()).FullName;
    public static string GetSolutionPath()
    {
        var currentDirPath = GetAssemblyDir();
        while (currentDirPath != null)
        {
            var fileInCurrentDir = Directory.GetFiles(currentDirPath).Select(f => f.Split(@"\").Last()).ToArray();
            var solutionFileName = fileInCurrentDir.SingleOrDefault(f => f.EndsWith(".sln", StringComparison.InvariantCultureIgnoreCase));
            if (solutionFileName != null)
                return Path.Combine(currentDirPath, solutionFileName);

            currentDirPath = Directory.GetParent(currentDirPath)?.FullName;
        }

        throw new FileNotFoundException("Cannot find solution file path");
    }
}

结果:

FileUtils.GetAssemblyFileName();
"CommonLibCore.dll"
FileUtils.GetAssemblyPath();
"G:\My Files\Programming\CSharp\Projects\MyAssemblyMVC\MyAssemblyConsole\bin\Debug\netcoreapp3.1\CommonLibCore.dll"
FileUtils.GetAssemblyDir();
"G:\My Files\Programming\CSharp\Projects\MyAssemblyMVC\MyAssemblyConsole\bin\Debug\netcoreapp3.1"
FileUtils.GetSolutionFileName();
"MyAssemblyMVC.sln"
FileUtils.GetSolutionPath();
"G:\My Files\Programming\CSharp\Projects\MyAssemblyMVC\MyAssemblyMVC.sln"
FileUtils.GetSolutionDir();
"G:\My Files\Programming\CSharp\Projects\MyAssemblyMVC"

enter image description here

关于c# - 如何从 Visual Studio Package 项目获取当前解决方案名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44699177/

相关文章:

c# - EntityFramework.sqlServerCompact和存储库模式MVVM

c# - 如何在dll中嵌入html文件并稍后编辑内容?

c# - 尝试重建Windows窗体的解决方案时出错

c++ - 如何增加 Visual Studio 中的错误限制?

c# - 如何查找 Windows 窗体面板中是否存在标签

c# - 如何使用 sharpmap 在地球上渲染一个国家的图像

c# - 为什么我会看到使用 native 代码的速度提高了约 20%?

.net - VSSDK : can't build solution with mixed style csproj-projects containing VSIX-projects

visual-studio-code - 是否可以打开和编辑 vsix 包(VS 代码的扩展文件)?如果是,那么如何?

c# - VSIX newtonsoft 不在包中 (VS>15.5) 抑制包