读书人

编程乐趣:发现小技艺

发布时间: 2012-09-16 17:33:16 作者: rapoo

编程乐趣:发现小技巧

如果有这样一个需求:当前文件运行在\bin\Debug\my.exe,现在要去\bin\Release\找一个文件my.txt,即\bin\Release\my.txt
用字符截取如下实现:

            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;            path = path.Substring(0, path.LastIndexOf(@"Debug\"));            string npath = path + @"Release\\my.txt";

其实完全没有这么麻烦,而且截取字符万一路径名做了修改就麻烦了。
还有一个简单方法,以前只知道在dos命令中..表示目录的上一级。其实在程序中拼接路径时也可以用的。
比如:\bin\Debug\..\Release\与\bin\Release\表示的是一样的目录。
而且如果是文件的话!File.Exists或者文件夹的话Directory.Exists都可以进行判断。
上面就可以一句话就实现了:

            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;           string npath  = path + @"..\Release\my.txt";

其实在程序中有很多小技巧,只要我们平时多写代码,多找偷懒的方法总会找到的。

读书人网 >编程

热点推荐