最简单的方法来从URL读取到.NET字符串 [英] Easiest way to read from a URL into a string in .NET
本文介绍了最简单的方法来从URL读取到.NET字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于字符串的URL:
http://www.example.com/test.xml
什么是从服务器(由URL指向)下载该文件的内容为一个字符串在C#中最简单/最简洁的方式?
我做的目前的方法是:
的WebRequest请求= WebRequest.Create(http://www.example.com/test.xml);
WebResponse的响应= request.GetResponse();
流数据流= response.GetResponseStream();
StreamReader的读者=新的StreamReader(数据流);
字符串responseFromServer = reader.ReadToEnd();
这是一个很大code的可能基本上是一条线:
字符串responseFromServer = ???? GetStringFromUrl(http://www.example.com/test.xml);
请注意:
- 我知道我可以把它包起来 - 我只是事情可能有一个更简单的方法
- 我不担心异步调用 - 这是不是生产code
解决方案
使用(Web客户端的客户端=新的WebClient()){
字符串s = client.DownloadString(URL);
}
Given a URL in a string:
http://www.example.com/test.xml
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#?
The way I'm doing it at the moment is:
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 know I can wrap it - I just thing there's probably an easier way
- 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屋!
查看全文