从 URL 读取到 .NET 中的字符串的最简单方法 [英] Easiest way to read from a URL into a string in .NET

查看:20
本文介绍了从 URL 读取到 .NET 中的字符串的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串中的 URL:

Given a URL in a string:

http://www.example.com/test.xml

将文件内容从服务器(由 url 指向)下载到 C# 中的字符串的最简单/最简洁的方法是什么?

What's the easiest/most succinct way to download the contents of the file from the server (pointed to by the url) into a string in C#?

我目前的做法是:

WebRequest request = WebRequest.Create("http://www.example.com/test.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

很多代码基本上可以是一行:

That's a lot of code that could essentially be one line:

string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml");

注意:我不担心异步调用 - 这不是生产代码.

Note: I'm not worried about asynchronous calls - this is not production code.

推荐答案

using(WebClient client = new WebClient()) {
   string s = client.DownloadString(url);
}

这篇关于从 URL 读取到 .NET 中的字符串的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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