Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to go one step backwards in path in C#

Tags:

c#

filepath

I want to get the path that my application is located in. I get the physical path by following code:

string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;

I get something like this as the result:

D:\\Projects\\UI\\IAC.SMS.MvcApp\\

I know that I can sepetare the string by "\" and combine them together. But is there an easy way to go one step back and get this?

D:\\Projects\\UI\\
like image 292
dieKoderin Avatar asked Feb 12 '23 05:02

dieKoderin


2 Answers

You're looking for Directory.GetParent method.

var directoryName = Path.GetDirectoryName("D:\\Projects\\UI\\IAC.SMS.MvcApp\\");
var parentName = Directory.GetParent(directoryName).FullName;

Or

var parentName = new DirectoryInfo("D:\\Projects\\UI\\IAC.SMS.MvcApp\\").Parent.FullName;
like image 187
Sriram Sakthivel Avatar answered Feb 13 '23 19:02

Sriram Sakthivel


Directory.GetParent will work in some cases, but it involves a performance penalty due to the creation of a DirectoryInfo object which will be populated with all sorts of information about the directory that may not be needed (e.g. creation time). I'd recommend Path.GetDirectoryName if all you need is the path, especially since with this method the path doesn't have to exist and you don't have to have permission to access it for the call to succeed.

var filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;

var parent = Path.GetDirectoryName(filePath);
like image 43
Mike Ness Avatar answered Feb 13 '23 19:02

Mike Ness