1

I know this is asked many times, but I couldn't exactly find what I need.

I want to get the server path and add image path to that. I did that

string mypath = Request.Url.GetLeftPart(UriPartial.Authority);
string uploadPath = Path.Combine(mypath, "Upload/Images/");
Response.Write(uploadPath);

This printed http://localhost\Upload/Images/, why is there a \ in the middle of the path.

I fixed it by adding / to mypath like this

string mypath = Request.Url.GetLeftPart(UriPartial.Authority) + "/";

Is this the correct way? or is there is any better way to do this?

Saahithyan Vigneswaran
  • 6,841
  • 3
  • 35
  • 45

2 Answers2

2

It is because Path.Combine is meant to combine typical directory path, something like:

C:\MyDir\MyDir2\MyMyDir

where the separator is \, not URL where the separator is /:

http://stackoverflow.com/questions/37249357/in-path-combine-in-c-sharp/37249373#37249373

If you want to combine URL path, you could use Uri instead:

Uri baseUri = new Uri(mypath);
Uri myUri = new Uri(baseUri, "Upload/Images/");
Ian
  • 30,182
  • 19
  • 69
  • 107
0

You should use Uri class for URLs, as Path.Combine is used for directory path operations.

Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI.

Uri baseUri = new Uri(mypath);
Uri myUri = new Uri(baseUri, "Upload/Images/");
string uploadPath = myUri.AbsoluteUri;

And to get the URL, AbsoluteUri property can be used.

Satpal
  • 132,252
  • 13
  • 159
  • 168