Path functions for URL

你说的曾经没有我的故事 提交于 2019-12-19 17:47:05

问题


I want to use functions of Path class (GetDirectoryName, GetFileName, Combine,etc.) with paths in URL format with slash (/).

Example of my path:

"xxx://server/folder1/folder2/file"

I tried to do the job with Path functions and in the end just replaced the separator.

I've found that the GetDirectoryName function does not correctly replace the slashes:

Path.GetDirectoryName(@"xxx://server/folder/file") -> @"xxx:\server\folder"

Like you see one slash is lost.

How can I cause the Path functions to use the 'alternative' separator?

Can I use another class with the same functionality?


回答1:


I'm afraid GetDirectoryName, GetFileName, Combine,etc. use Path.DirectorySeparatorChar in the definition and you want Path.AltDirectorySeparatorChar.

And since Path is a sealed class, I think the only way to go about is string replacement.You can replace Path.DirectorySeparatorChar('\') with Path.AltDirectorySeparatorChar('/') and Path.VolumeSeparatorChar(':') with ":/"




回答2:


For GetDirectoryName(), you can use

pageRoot = uri.Remove(uri.LastIndexOf('/') + 1);



回答3:


Have you considered using a combination of System.Uri, System.UriBuilder, and (if necessary) custom System.UriParser subclass(es)?




回答4:


If the URI is a local file URI of the form file://whatever then you can call string path = new Uri(whatever).LocalPath and call the Path methods on it. If you cannot guarantee the Uri is to a local path, you cannot guarantee components of the Uri correspond to machines, folders, files, extensions, use directories, separator characters, or anything else.



来源:https://stackoverflow.com/questions/5624787/path-functions-for-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!