System.IO相对路径

时间:2013-01-09 21:36:07

标签: c# path .net

我正在尝试从我的解决方案中读取文件。我想知道如何使用相对路径找到该文件。我的解决方案包含 3个项目。我想要读取的文件位于项目A 中,但正在读取它的代码位于项目B 中。如果我使用..\file.txt将我带到 Project B 而不是 Project A 。如果我使用Application.StartPath 我得到了

C:\\Users\\Linda\\AppData\\Local\\Microsoft\\VisualStudio\\10.0\\Extensions\\tangible\\t4 editor\\2.1.1

而我需要找到我开发代码C:\Sp_CodeGenerator\...

的目录

我也尝试过使用

Environment.GetFolderPath

Directory.GetCurrentDirectory();
System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(Application.ExecutablePath))'`
System.AppDomain.CurrentDomain.BaseDirectory.ToString();

但这些都会产生相同的结果,并将我带到Visual Studio Program文件,而不是在硬盘上创建解决方案的位置。

还有什么我应该尝试的吗?

1 个答案:

答案 0 :(得分:4)

听起来像是你在t4模板中执行路径相关的代码?这实际上会影响答案,因为处理路径的所有常规方法都将在visual studio和你正在使用的t4编辑器插件的上下文中。

您需要访问ITextTemplatingEngineHost才能正确解析路径。

在模板中添加特定于主机的导演

<#@template language="c#" hostspecific="true" #>

然后您可以通过

访问它
this.Host.ResolvePath(path);

//also available (Gets the path and file name of the text template that is being processed.)
//this.Host.TemplateFile

请参阅http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.texttemplating.itexttemplatingenginehost(v=vs.110).aspx