使用C#从网站读取数据

编程入门 行业动态 更新时间:2024-10-28 02:23:22
本文介绍了使用C#从网站读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个网页,除了一些字符串之外,什么都没有.没有图像,没有背景色或其他任何东西,只有一些长度不那么长的纯文本.

I have a webpage which has nothing on it except some string(s). No images, no background color or anything, just some plain text which is not really that long in length.

我只是想知道,什么是在网页中传递字符串的最佳方式(我的意思是最快,最有效),以便我可以将其用于其他用途(例如,在文本框中显示)?我知道WebClient,但是我不确定它是否会按照我想要的去做,而且我什至不想尝试它,即使它确实起作用了,因为我上次这样做大约花了30秒一个简单的操作.

I am just wondering, what is the best (by that, I mean fastest and most efficient) way to pass the string in the webpage so that I can use it for something else (e.g. display in a text box)? I know of WebClient, but I'm not sure if it'll do what I want it do and plus I don't want to even try that out even if it did work because the last time I did it took approximately 30 seconds for a simple operation.

任何想法都会受到赞赏.

Any ideas would be appreciated.

推荐答案

WebClient类应具有处理您描述的功能的能力,例如:

The WebClient class should be more than capable of handling the functionality you describe, for example:

System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData("www.yoursite/resource/file.htm"); string webData = System.Text.Encoding.UTF8.GetString(raw);

或(进一步来自Fredrick在评论中的建议)

or (further to suggestion from Fredrick in comments)

System.Net.WebClient wc = new System.Net.WebClient(); string webData = wc.DownloadString("www.yoursite/resource/file.htm");

当您说花了30秒时,您可以再扩展一点吗?有许多原因可以说明为什么会发生这种情况.缓慢的服务器,互联网连接,狡猾的实现方式等.

When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.

您可以再降低一个级别,并实现类似这样的功能:

You could go a level lower and implement something like this:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("www.yoursite/resource/file.htm"); using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8)) { streamWriter.Write(requestData); } string responseData = string.Empty; HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse(); using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream())) { responseData = responseReader.ReadToEnd(); }

但是,最终,WebClient类为您包装了此功能.因此,我建议您使用WebClient并调查30秒延迟的原因.

However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

更多推荐

使用C#从网站读取数据

本文发布于:2023-06-03 06:19:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/470185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   网站

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!