I created a Visual Studio Package project with a custom menu I would like to add to Visual Studio (2013).
I'm trying to get the current solution name/directory in run time.
I've tried this solution:
DTE dte = (DTE)GetService(typeof(DTE));
string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
but dte.Solution.FullName
is always empty.
I though it is related to the fact that i'm running in debug mode and a new instance of Visual Studio is created for this purpose, but it happened also when I installed my extension and ran it from Visual Studio as I ran any menu.
Any ideas what i'm missing?
Thanks
PS the solution I used is taken from here:
How do you get the current solution directory from a VSPackage?
Try this:
var solutionName = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
You need to be using System.IO and System.Diagnostics . There also might be some file extensions at the end of solutionName that you will need to trim.
You can achieve it by finding the .sln
file up the directory tree from your executing assembly:
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");
}
}
Results:
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.