是否有一种简单的方法来打开Uri并得到它指向的任何东西?(C#)

Mat*_*ley 8 c# uri

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

我想打开文件的Uri指向,无论是本地,网络,http,无论如何,并将内容读入字符串.有没有一种简单的方法可以做到这一点,或者我是否必须尝试解决一些问题,想Uri.IsFile弄清楚如何尝试打开它?

Meh*_*ari 11

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();
}
Run Code Online (Sandbox Code Playgroud)

无论如何都无济于事.它的工作原理为file://,http://https://ftp://默认.但是,您可以注册自定义URI处理程序,WebRequest.RegisterPrefix以使其也适用于那些.


Phi*_*ert 5

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

using(WebClient client = new WebClient())
{
    string contents = client.DownloadString(uri);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您需要多个线程 - 使用多个`WebClient`实例.这里没有线程安全问题...... (3认同)