2013-05-31 113 views

回答

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應用程序運行的任何目錄,你可以得到它,將其降低一級,然後粘貼「文件夾」以獲取新的兄弟目錄。

+0

如果我不得不在我的webb應用程序中使用類庫。而在類庫中,我必須獲取webb應用程序域路徑。我將如何實現這一點。 –

+0

您是否暗示類庫會在不知道Web應用程序的上下文中運行?你需要替代'HttpRuntime.AppDomainAppPath'嗎? – DonBoitnott

+0

是的,我可以。它將駐留在類庫中。 –

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 
+0

如果在路徑中存在具有相同名稱的文件夾,該文件也會發生變化。 –

+0

@StylesYoung你是什麼意思改變?你的目的是什麼? –

+0

我認爲他的意思是說你把它寫得太直接了......該路徑可能並不總是字面上的「C:\ path \ webapp」....它可能是「C:\ mydir \ anotherdir \ webapp \ thirddir \ webapp」。在你的解決方案中,該路徑被String.Replace()破壞。 – DonBoitnott

相關問題