首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

编程乐趣:向上取N层索引

2013-10-08 
编程乐趣:向上取N层目录编程中总少不了和目录打交道,尤其是当运行目录下有很多子目录,比如配置文件的目录,

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

编程中总少不了和目录打交道,尤其是当运行目录下有很多子目录,比如配置文件的目录,第三方dll的目录等,截取目录总会用到。前面也使用过“..”的方式来取上一级目录(http://blog.csdn.net/yysyangyangyangshan/article/details/7968259),不过总是有所限制。
于是写了一个向上取N级目录的方法,其实也无技术含量,无非是对字符串的截取,不过重在方便。

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;        }    }


 

测试

  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();        }    }


  结果
编程乐趣:向上取N层索引

代码:http://download.csdn.net/detail/yysyangyangyangshan/6337471

热点排行