【编程乐趣:向上取N层目录】

编程中总少不了和目录打交道,尤其是当运行目录下有很多子目录,比如配置文件的目录,第三方dll的目录等,截取目录总会用到。前面也使用过“..”的方式来取上一级目录,不过总是有所限制。
于是写了一个向上取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(); 
      } 
  } 

posted @ 2013-10-04 10:48  来自你520的末班车  阅读(226)  评论(0编辑  收藏  举报