[英]How to get the current solution name from a Visual Studio Package project?
我創建了一個帶有自定義菜單的 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 運行它時也會發生這種情況。
任何想法我缺少什么?
謝謝
PS我使用的解決方案取自這里:
如何從 VSPackage 獲取當前解決方案目錄?
嘗試這個:
var solutionName = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
and .您需要使用和 。 that you will need to trim.在的末尾可能還有一些文件擴展名,您需要對其進行修剪。
您可以通過從正在執行的程序.sln
在目錄樹中查找.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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.