有一个简单的方法来打开一个URI,并得到任何它指向? (C#) [英] Is there an easy way to open a Uri and get whatever it points to? (C#)

查看:87
本文介绍了有一个简单的方法来打开一个URI,并得到任何它指向? (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递给我的类的构造函数乌里对象。



我要打开的文件中的乌里点,无论是本地,网络,HTTP,无论和内容读到一个字符串。是否有这样做的一个简单的方法,或做我必须努力工作过,比如 Uri.IsFile 事情弄清楚如何尝试打开它?


解决方案

 静态字符串GetContents(URI URI){
使用(VAR响应= WebRequest.Create (URI).GetResponse())
使用(VAR流= response.GetResponseStream())
使用(VAR读者=新的StreamReader(流))
返回reader.ReadToEnd();
}



这不会对工作什么。它适用于文件:// 的http:// 的https:// 的ftp:// 默认情况下。但是,您可以使用 WebRequest.RegisterPrefix注册自定义的URI处理程序 ,使之成为那些正常工作。


I have a Uri object being passed to a constructor of my class.

I want to open the file the Uri points to, whether it's local, network, http, whatever, and read the contents into a string. Is there an easy way of doing this, or do I have to try to work off things like Uri.IsFile to figure out how to try to open it?

解决方案

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();
}

It won't work for whatever. It works for file://, http:// and https:// and ftp:// by default. However, you can register custom URI handlers with WebRequest.RegisterPrefix to make it work for those as well.

这篇关于有一个简单的方法来打开一个URI,并得到任何它指向? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆