获取与App域路径相同的目录中的文件夹

时间:2013-05-31 10:36:28

标签: c# asp.net

我有一个asp.net网络应用程序,我需要获取与我的网络应用程序在同一目录中的文件夹的字符串路径。 目前我正在使用此代码来获取添加域路径。

string appPath = HttpRuntime.AppDomainAppPath;

返回“c:/ path / webapp”,我需要“c:/ path / folder”。

感谢。

2 个答案:

答案 0 :(得分:2)

如果您想要更通用的方法,不需要知道起始文件夹:

//NOTE:  using System.IO;
String startPath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath);
Int32 pos = startPath.LastIndexOf(Path.DirectorySeparatorChar);
String newPath = Path.Combine(startPath.Substring(0, pos), "folder");  //replace "folder" if it's really something else, of course

这样,无论您的Web应用程序运行的目录是什么,您都可以获取它,将其降低一级,并添加“文件夹”以获取新的兄弟目录。

答案 1 :(得分:0)

您可以使用String.Replace方法。

  

返回一个新字符串,其中所有出现的指定字符串都在其中   当前实例将替换为另一个指定的字符串。

string appPath = HttpRuntime.AppDomainAppPath;
appPath = appPath.Replace("webapp", "folder");

这是DEMO

感谢DonBoitnott的评论,这是正确的答案;

string appPath = @"C:\mydir\anotherdir\webapp\thirddir\webapp";
int LastIndex = appPath.LastIndexOf("webapp", StringComparison.InvariantCulture);
string RealappPath = Path.Combine(appPath.Substring(0, LastIndex), "folder");
Console.WriteLine(RealappPath);

这将打印;

C:\mydir\anotherdir\webapp\thirddir\folder