I’m a rookie web developer creating a site in C#, in VS2005 and using a .master file.
I want to make each page in the site aware of its current location in the directory structure, so I can display the appropriate navigation links on each page.
I wrote the following code in the .master file to look up the directory structure relative to the current page. It works fine on my test server at localhost/mysite, but when I push to the public site at http://www.example.coom, the code breaks.
I figured out that the problem is with the “int depth = h-2” line. If I change it to h-1, it works on mysite.org. But that’s an ugly solution.
int nUrlSegments = this.Page.Request.Url.Segments.GetLength(0);
string[] thisPageArray = new string[nUrlSegments];
for (int i = 0; i < nUrlSegments; i++)
thisPageArray[i] = Page.Request.Url.Segments[i].ToString();
int h = 0;
while (!thisPageArray[h].Contains(".aspx"))
h++;
int depth = h - 2;
string pathToTop = "";
for (int j = 1; j <= depth; j++)
pathToTop = pathToTop + "../";
string currentpage = thisPageArray[nUrlSegments-1].ToString();
string currentdir = "";
if (nUrlSegments > 1)
currentdir = thisPageArray[nUrlSegments - 2].ToString();
What’s a better way to find each page’s place in the directory structure?
A friend of mine from the non-Internet world helped me answer this. For the record, here’s the solution I came up with using his advice: