有一个简单的方法来打开一个URI,并得到任何它指向? (C#)(Is there an easy

2019-09-17 08:45发布

我有一个Uri传递给我的类的构造函数对象。

我想打开该文件的Uri点,无论是本地,网络,HTTP,不管,并读取其中的内容为一个字符串。 是否有这样做的一个简单的方法,或者我必须努力工作过的东西像Uri.IsFile弄清楚如何尝试打开它?

Answer 1:

static string GetContents(Uri uri) {
    using (var response = WebRequest.Create(uri).GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream))
        return reader.ReadToEnd();
}

它不会对任何工作。 它适用于file://http://https://ftp://默认。 但是,您可以注册自定义URI处理器WebRequest.RegisterPrefix ,使之成为那些正常工作。



Answer 2:

最简单的方法是使用WebClient类:

using(WebClient client = new WebClient())
{
    string contents = client.DownloadString(uri);
}


文章来源: Is there an easy way to open a Uri and get whatever it points to? (C#)
标签: c# uri