例外:“不支持URI格式”


89

我有一个指向目录的绝对本地路径: "file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj"

但是,当我尝试将其放入DirectoryInfo的ctor中时,出现“不支持URI格式”异常。

我用谷歌搜索并查看了SO,但是我只看到带有远程路径的解决方案,而不是本地路径。我希望某种转换方法...

Answers:


189
string uriPath =
    "file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;

3
真好!我遇到了同样的问题,Google疯狂地搜索了它,效果很好。
杰里米·摩根

虽然它的解决方案可以正常工作,但只有一种情况失败了。如果该位置包含#,则本地路径将仅到达该位置。例如,如果您的路径是file:/// C:/foo/bar#/test.jpg,那么您将获得C:/ foo / bar而不是实际需要的文件。
DokutoMekki 2015年

2
你好 我希望该文件位于www.xxx.com/sitemap.xml。这个东西在本地主机上工作,但是在服务器上没有这样的目录。在这种情况下,如何分类?
这是一个陷阱

@ It'strap也许您正在寻找Server.MapPath
Andrew Morton

但是使用您的路径后,我将在其中创建更多文件夹,而不是在创建目录。看看stackoverflow.com/questions/63493899/...
HUD

1

试试这个

ImagePath = "http://localhost/profilepics/abc.png";
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();


0
     string ImagePath = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
        string a = "";
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            Stream receiveStream = response.GetResponseStream();
            if (receiveStream.CanRead)
            { a = "OK"; }
        }

        catch { }

1
尽管这段代码可以解决问题,但包括解释如何以及为什么解决该问题的说明,确实可以帮助提高您的帖子质量,并可能导致更多的投票。请记住,您将来会为读者回答问题,而不仅仅是现在问的人。请编辑您的答案以添加说明,并指出适用的限制和假设。
Artog
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.