简体   繁体   中英

Path.Combine on urls gives exception : The given path's format is not supported

I have an error in following code

Uri imagesrc = new Uri("http://somewebsite.com/demo/images/slideshow/29.jpg");
Image image = Image.FromFile(Path.Combine("/comph/", imagesrc.ToString()));

I have also tried following code - where /comph/ is my root directory

Image.FromFile(Path.Combine("/comph/","http://some_other_website.com/demo/images/slideshow/29.jpg");

The above image URL is correct when I paste this URL in browser it shows the image.

With the above code an exception is raised:

The given path's format is not supported.

What is wrong with this code ?

Path.Combine does not support urls.

You will have to translate the url to a (relative) file path first if you want to use Path.Combine

If you want to manipulate urls you can use the Url constructor that takes a base url and a relative url and combines them .

A quick (but a little bit dirty way) is to take the local part from an Uri, strip the root "/" and then use Path.Combine:

Uri imagesrc = new Uri("http://somewebsite.com/demo/images/slideshow/29.jpg");    
string target = Path.Combine("comph", imagesrc.LocalPath.TrimStart('/'));

the result is "comph\\demo/images/slideshow/29.jpg" , which will work but you could replace / with \\ for cosmetics.

Do not use Path.Combine for URLs. That method is meant to be used with local filesystem paths!

While it might not work in all cases, you can often use new Uri(Uri, Uri) to combine URLs:

// using System;
var absoluteUri = new Uri('http://example.com/path/');
var relativeUri = new Uri('./more', UriKind.Relative);
var combinedUri = new Uri(absoluteUri, relativeUri);

Appending a path to an existing URL seems to work only correctly when the existing URL's path ends with a / ; otherwise the last path segment might be missing in the combined URL.

(I haven't tested what happens when the existing URL already has a query string or fragment, btw. Make sure to test this yourself if it might be relevant in your case.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM