URL格式不受支持。

3

我正在使用File.OpenRead方法读取文件,我将提供此路径

   http://localhost:10001/MyFiles/folder/abc.png

我也尝试过这个方法,但没有成功

http://localhost:10001//MyFiles//abc.png

但是它在输出时出现了以下问题:

不支持URL格式

当我提供物理路径时,如下所示,它可以正常工作:

d:\MyFolder\MyProject\MyFiles\folder\abc.png

我如何将文件路径转换为Http路径?

这是我的代码:

public FileStream GetFile(string filename)
{
    FileStream file = File.OpenRead(filename);
    return file;
}

这可能是你的答案:https://dev59.com/kXNA5IYBdhLWcg3wNrAy - Bart Friederichs
使用 Server.MapPath("//MyFiles")+"//abc.png" 作为文件名。 - Annie
你需要使用 Server.MapPath(),因为文件操作需要物理文件路径而不是虚拟路径。在你的情况下,你应该使用 string filePath=Server.MapPath("~/MyFiles/folder/abc.png"); - Rajesh Kumar
5个回答

9

请看WebClient (MSDN文档),它有许多实用方法可用于从网络下载数据。

如果您想将资源作为Stream获取,请尝试:

using(WebClient webClient = new WebClient())
{
    using(Stream stream = webClient.OpenRead(uriString))
    {
        using( StreamReader sr = new StreamReader(stream) )
        {
            Console.WriteLine(sr.ReadToEnd());
        }
    }
}

3
你可以使用WebClient,就像其他答案中建议的那样,或者像这样获取相对路径:
var url = "http://localhost:10001/MyFiles/folder/abc.png";

var uri = new Uri(url);
var path = Path.GetFileName(uri.AbsolutePath);

var file = GetFile(path);
// ...

一般来说,你应该摆脱绝对URL。

2
最佳的下载HTML方式是使用WebClient类。您可以像这样操作:
    private string GetWebsiteHtml(string url)
    {
        WebRequest request = WebRequest.Create(url);
        WebResponse response = request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string result = reader.ReadToEnd();
        stream.Dispose();
        reader.Dispose();
        return result;
    }

如果你想进一步处理HTML,例如提取图像或链接,那么你需要使用一种称为HTML scrapping的技术。

目前最好的方法是使用HTML Agility Pack

此外,WebClient类的文档可以在MSDN上找到。


1

这里 我找到了这个代码片段。可能正好符合你的需求:

using(WebClient client = new WebClient()) {
   string s = client.DownloadFile(new Uri("http://.../abc.png"), filename);
}

它使用了 WebClient 类。

0

要将 file:// URL 转换为 UNC 文件名,您应该使用 Uri.LocalPath 属性,如文档所述

换句话说,您可以这样做:

public FileStream GetFile(string url)
{
    var filename = new Uri(url).LocalPath;
    FileStream file = File.OpenRead(filename);
    return file;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接