Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Uri from base without trailing slash and relative parts

Tags:

.net

uri

I am having a problem with Uri constructor. Results differ on whether base path ends with slash or not.

var baseWithSlash = new Uri("c:\\Temp\\");
var baseNoSlash = new Uri("c:\\Temp");

var relative = "MyApp";

var pathWithSlash = new Uri(baseWithSlash, relative);  // file:///c:/Temp/MyApp
var pathNoSlash = new Uri(baseNoSlash, relative);      // file:///c:/MyApp

The first result is the one I expect even if there's no slash in base path.

My main problem is that base path comes from user input.

What's the best way to achieve correct result even if user specifies path without trailing slash?

like image 755
Konstantin Spirin Avatar asked Jan 24 '23 02:01

Konstantin Spirin


1 Answers

This is to be expected IMO. After all, consider the URI for "hello.jpg" relative to

 http://foo.com/site/index.html

It's

 http://foo.com/site/hello.jpg

right?

Now if you know that your user is entering a URI representing a directory, you can make sure that the string has a slash on the end. The problem comes if you don't know whether they're entering a directory name or not. Will just adding a slash if there isn't one already work for you?

string baseUri = new Uri(userUri + userUri.EndsWith("\\") ? "" : "\\");

That's assuming (based on your example) that they'll be using backslashes. Depending on your exact circumstance, you may need to handle forward slashes as well.

like image 129
Jon Skeet Avatar answered Apr 07 '23 02:04

Jon Skeet