You may like this more general solution, which depends on the search for the *.sln solution file, scanning all the parent directories from the current or selected one, at the same time closing the case of finding the solution catalog!
public static class VisualStudioProvider { public static DirectoryInfo TryGetSolutionDirectoryInfo(string currentPath = null) { var directory = new DirectoryInfo( currentPath ?? Directory.GetCurrentDirectory()); while (directory != null && !directory.GetFiles("*.sln").Any()) { directory = directory.Parent; } return directory; } }
Using:
// get directory var directory = VisualStudioProvider.TryGetSolutionDirectoryInfo(); // if directory found if (directory != null) { Console.WriteLine(directory.FullName); }
In your case:
// resolve file path var filePath = Path.Combine( VisualStudioProvider.TryGetSolutionDirectoryInfo() .Parent.FullName, "filename.ext"); // usage file StreamReader reader = new StreamReader(filePath);
Enjoy it!
Now a warning .. Your application should be an agnostic solution - if this is not a personal project for any decision processing tool, I would not mind. Understand that your application, once distributed to users , will be in a folder without a solution. Now you can use the "anchor" file. For instance. search for parent folders like me and check for empty app.anchor or mySuperSpecificFileNameToRead.ext ; P If you want me to write a way that I can, just let me know.
Now you really will like it !: D
source share