我有一个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以使其也适用于那些.
最简单的方法是使用WebClient类:
using(WebClient client = new WebClient())
{
string contents = client.DownloadString(uri);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7102 次 |
| 最近记录: |