问题描述
我需要获取解决方案文件 (.sln) 所在的路径.我尝试使用以下几行:
I need to get the path where the solution file (.sln) is located. I try with this lines:
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,"abc.txt");
// Read the file as one string.
string text = System.IO.File.ReadAllText(startupPath);
当我运行它时,我得到一个未经授权的访问异常".当我手动"放置路径时:C:\Users\yabej\source\repos\tutoriales\Proyecto 0.1
它可以工作!
When I run it, I get an "Unauthorized Access Exception". When I put the path "manually": C:\Users\yabej\source\repos\tutoriales\Proyecto 0.1
it works!
但是我需要一个自动"确保在不同计算机上运行项目时路径正确的解决方案
However I need an "automatic" solution to be sure that the path will be correct when I run my project on different computers
推荐答案
获得正确解决方案路径的正确方法在使用 EnvDTE100 NuGet 包的 Visual Studio 2019 中对我有用.
The proper way to get the right solution path worked for me in Visual Studio 2019 with the EnvDTE100 NuGet Package.
说明:仅适用于单个 VS 实例打开(来源 @junliantolovich)
确保为您的 Visual Studio 使用正确的 ProgId:
Be sure use the correct ProgId for your Visual Studio:
using System;
using EnvDTE80;
using System.IO;
using System.Runtime.InteropServices;
namespace Test
{
public class Program
{
public static void Main()
{
var di = GetSolutionDirInfo();
Console.WriteLine(di.FullName);
}
public static DirectoryInfo GetSolutionDirInfo()
{
// Use here the ProgId of your Visual Studio
// VS 2010 -> "VisualStudio.DTE.10.0"
// VS 2012 -> "VisualStudio.DTE.11.0"
// VS 2013 -> "VisualStudio.DTE.12.0"
// VS 2015 -> "VisualStudio.DTE.14.0"
// VS 2017 -> "VisualStudio.DTE.15.0"
// VS 2019 -> "VisualStudio.DTE.16.0"
var progId = "VisualStudio.DTE.16.0";
var dte2 = (DTE2)Marshal.GetActiveObject(progId);
return Directory.GetParent(dte2.Solution.FullName);
}
}
}
这篇关于c#中如何获取解法路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!