我知道这个问题被问了很多次,但我找不到我需要的东西。
我想获得服务器路径并添加图像路径。我做了
string mypath = Request.Url.GetLeftPart(UriPartial.Authority);
string uploadPath = Path.Combine(mypath, "Upload/Images/");
Response.Write(uploadPath);
这个打印的http://localhostUpload/Images/
,为什么在路径的中间有一个。
我通过像这个一样将/
添加到mypath
来修复它
string mypath = Request.Url.GetLeftPart(UriPartial.Authority) + "/";
这是正确的方法吗?或者有更好的方法吗?
这是因为Path.Combine
旨在组合典型的目录路径,类似于:
C:MyDirMyDir2MyMyDir
其中分隔符为,而不是其中分隔符是
/
:的URL
http://stackoverflow.com/questions/37249357/in-path-combine-in-c-sharp/37249373#37249373
如果你想合并URL路径,你可以使用Uri
代替:
Uri baseUri = new Uri(mypath);
Uri myUri = new Uri(baseUri, "Upload/Images/");
您应该将Uri
类用于URL,因为Path.Combine
用于目录路径操作。
提供统一资源标识符(URI)的对象表示,并方便地访问URI的各个部分。
Uri baseUri = new Uri(mypath);
Uri myUri = new Uri(baseUri, "Upload/Images/");
string uploadPath = myUri.AbsoluteUri;
为了获得URL,可以使用AbsoluteUri属性。