C#获得项目路径信息

I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.

Path.Combine makes sure you never go wrong with slashes.

.. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.

Some basic .. behavior:
1.If there is a file name, .. will chop that off:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\
2.If the path is a directory, .. will move up a level:

Path.Combine(@"D:\Grandparent\Parent\", "..") => D:\Grandparent\
3...\.. follows the same rules, twice in a row:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", @"..\..") => D:\
4.And this has the exact same effect:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", "..", "..") => D:

string directory = System.Environment.CurrentDirectory;
System.Console.WriteLine(directory);

string dir = Directory.GetParent(Directory.GetParent(Directory.GetParent(directory).FullName).FullName).FullName;

 

posted @ 2017-06-23 14:58  genezhao  阅读(321)  评论(0编辑  收藏  举报