Simplify a relative URL

You can do it with one-liner:

new Uri(new Uri("http://example.com/"), url).AbsolutePath.TrimStart('/');

The following test shows the results:

        [Theory]
        [InlineData("./foo", "foo")]
        [InlineData("/foo", "foo")]
        [InlineData("foo", "foo")]
        [InlineData("foo/./bar", "foo/bar")]
        [InlineData("/foo/./bar", "foo/bar")]
        [InlineData("/foo/../bar", "bar")]
        [InlineData("foo/../bar", "bar")]
        public void Test(string url, string expected)
        {
            var result = new Uri(new Uri("http://example.com/"), url).AbsolutePath.TrimStart('/');
            Assert.Equal(expected, result);
        }

Of course, if you want to leave / in the beginning just remove TrimStart('/')

Tags:

C#

.Net