WebClient读取网络数据

    C#读取网络文件数据,可以由下面这个函数实行:System.Net.WebClient类可以支持直接从网络上读取数据,下面列举下有用的方法:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    WebClient.DownloadData (String)                                  以 Byte 数组形式通过指定的 URI 下载资源

    WebClient.DownloadData (Uri)                                       以 Byte 数组形式通过指定的 URI 下载资源

    WebClient.DownloadFile (String, String)                        将具有指定 URI 的资源下载到本地文件

    WebClient.DownloadFile (Uri, String)                             将具有指定 URI 的资源下载到本地文件

    WebClient.DownloadString (String)                                以 String 形式下载指定的资源

    WebClient.DownloadString (Uri)                                     以 Uri 形式下载指定的资源

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     对于以上这些方法,均有xxxAsync方法与之对应,目的是使得xxx方法不会阻止调用线程。如WebClient.DownloadFileAsync (Uri, String)方法,就是异步下。

    其中,WebClient.DownloadData (Uri) 方法返回Byte数组,容易出现中文乱码问题,因为中文是双字节数据,而返回byte类型,因此这时候,中文便容易出现乱码,解决方案可能是转换为unicode什么的吧。所以个人建议用WebClient.DownloadString(Uri),如果此时还出现乱码问题,便是字符集问题了,可以用

                               WebClient client = new WebClient();
                               string s = client.DownloadString("http://www.cnblogs.com");

                               s=Encoding.UTF8.GetString(Encoding.Default.GetBytes(s);

这样便可以了。

 

 

----------------------

StreamReader sr = new StreamReader(resStream, enc); //命名空间:System.IO。 StreamReader 类实现一个 TextReader (TextReader类,表示可读取连续字符系列的读取器),使其以一种特定的编码从字节流中读取字符。 
ContentHtml.Text = sr.ReadToEnd(); //输出(HTML代码),ContentHtml为Multiline模式的TextBox控件
resStream.Close(); 
sr.Close();

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2021-12-22
  • 2021-12-31
  • 2022-12-23
  • 2021-05-13
  • 2021-11-24
猜你喜欢
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案