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

时间:2017-06-22 12:15:16

标签: c# visual-studio vsix solution envdte

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

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

我尝试过这个解决方案:

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

dte.Solution.FullName始终为空。

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

我缺少什么想法?

由于

P.S。我使用的解决方案来自这里:
How do you get the current solution directory from a VSPackage?

2 个答案:

答案 0 :(得分:0)

试试这个:

var solutionName = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);

您需要使用 System.IO System.Diagnostics solutionName 末尾可能还有一些文件扩展名需要修剪。

答案 1 :(得分:0)

您可以通过在执行程序集的目录树中找到.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