How to take a step backwards on a path in C #
I want to get the path where my application is located. I am getting the physical path by following the code:
string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
The result is something like this:
D:\\Projects\\UI\\IAC.SMS.MvcApp\\
I know that I can pass the string "\" and concatenate them. But is there an easy way to take one step back and get this?
D:\\Projects\\UI\\
source to share
You are looking for the 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;
source to share
Directory.GetParent will work in some cases, but this is a performance limitation due to the creation of a DirectoryInfo object that will be populated with all sorts of directory information that might not be needed (for example, creation time). I would recommend Path.GetDirectoryName if all you need is a path, especially since with this method the path should not exist and you should not have permission to access it to invoke successfully.
var filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
var parent = Path.GetDirectoryName(filePath);
source to share