編程中總少不了和目錄打交道,尤其是當運行目錄下有很多子目錄,比如配置文件的目錄,第三方dll的目錄等,截取目錄總會用到。前面也使用過“..”的方式來取上一級目錄(http://blog.csdn.net/yysyangyangyangshan/article/details/7968259),不過總是有所限制。 於是寫了一個向上取N級目錄的方法,其實也無技術含量,無非是對字符串的截取,不過重在方便。 [csharp] public class ToolMethods { /// <summary> /// 取向上幾層的目錄 /// </summary> /// <param name="sourcePath"></param> /// <param name="deep"></param> /// <returns></returns> public static string GetPathByParentDeep(string sourcePath, int deep) { if (string.IsNullOrEmpty(sourcePath) || deep < 0) { return sourcePath; } string tempPath = sourcePath.Replace(@"/", @"\"); if (tempPath.EndsWith(@"\")) { deep += 1; } for (int i = 0; i < deep; i++) { if (!tempPath.Contains(@"\")) { break; } tempPath = tempPath.Substring(0, tempPath.LastIndexOf(@"\")); } return tempPath; } } 測試 [csharp] class Program { static void Main(string[] args) { string startPath = Environment.CurrentDirectory; Console.WriteLine(@"當前運行目錄:" + startPath); string path1 = ToolMethods.GetPathByParentDeep(startPath, 1); Console.WriteLine(@"當前運行目錄向上取一層:" + path1); string path3 = ToolMethods.GetPathByParentDeep(startPath, 3); Console.WriteLine(@"當前運行目錄向上取三層:" + path3); Console.ReadLine(); } }