Search code examples
c#asp.nettrim

Generating a file path and trimming ".aspx"


I want to generate the pages file path, then trim .aspx... I've tried the code below but this isn't working. New to the Windows world, I'm used to Linux so please be nice :D

Edit: Error for my code below is: Compiler Error Message: CS1525: Invalid expression term '[',

but once that's fixed it keeps spitting out errors. I believe I may be just getting the fundamentals of this task wrong.

public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
    string thepath = Page.ResolveUrl(Request.RawUrl);
    string thepath = Trim([.aspx] trimChars);
    string[] a = thepath.Split('/');
    for (int i = 0; i < a.Length - 1; i++)
    {
        thepath += a[i].ToLower() + "/"; ;
    }
    Canonical.Text = "<link rel=\"canonical\" href=\"https://example.com" + thepath.ToLower() + "\" />\n";
}
}

Solution

  • [.aspx] isn't valid and you're not trimming anything. change it to the following:

    string thepath = Page.ResolveUrl(Request.RawUrl);
    thepath = thepath.Replace(".aspx","");
    

    This will do as you need, but if you have .aspx anywhere else in the string it'll replace there too. If you want just the end, you can still use TrimEnd but it's a bit hacky IMHO.

    string thepath = Page.ResolveUrl(Request.RawUrl);
    thepath = thepath.TrimEnd(".aspx".ToCharArray());