WebClient(1、2、3)介绍了读数据流和下载远程网页数据流的相关内容。本节开始介绍向url 远程主机可写数据流写数据。同时还将介绍相关的的上传数据到远程主机上。
请看入如下事例代代码,及相关的代码实现其代码的剖析:
2
//
写入数据流
3 byte [] postdata = System.Text.Encoding.ASCII.GetBytes( string .Format( " {0}writeInfo " ,DateTime.Now.ToString( " yyyy-MM-dd HH:ss " )));
4 WebClient client = new WebClient();
5 Stream stream = client.OpenWrite( " http://localhost:85/uploadfile.txt " , " PUT " );
6 stream.Write(postdata, 0 , postdata.Length);
7 stream.Close();
3 byte [] postdata = System.Text.Encoding.ASCII.GetBytes( string .Format( " {0}writeInfo " ,DateTime.Now.ToString( " yyyy-MM-dd HH:ss " )));
4 WebClient client = new WebClient();
5 Stream stream = client.OpenWrite( " http://localhost:85/uploadfile.txt " , " PUT " );
6 stream.Write(postdata, 0 , postdata.Length);
7 stream.Close();
如上事例可以向远程主机谢数据,其实最关键的是获取一个可写的数据流,获取一个可写数据流向数据流中写入数据。其中WebClient.OpeWirte 核心实现其功能的是通过 WebRequest
创建一个事例后返回一个网络可写的数据流,代码分析如下:
1
2
WebRequest request
=
WebRequest.Create(
new
Uri(
"
http://localhost:85/uploadfile.txt
"
));
3 request.Credentials = CredentialCache.DefaultCredentials;
4 request.Method = " PUT " ;
5 Stream stream = request.GetRequestStream();
6 stream.Write(postdata, 0 , postdata.Length);
7 stream.Close();
3 request.Credentials = CredentialCache.DefaultCredentials;
4 request.Method = " PUT " ;
5 Stream stream = request.GetRequestStream();
6 stream.Write(postdata, 0 , postdata.Length);
7 stream.Close();
如上2-4行实现了WebClient.openWrite的功能,这里只是些了核心的代码,真实是现实功能比这里要多许多相关的条件。 还有一点是需要把网络扩展是Web服务扩展中的WebDAV改为允许,默认是静止的。还有用于异步写数据的OpenWriteAsync ,有用篇幅限制。这里就不做过多介绍。
由于时间限制,由于时间时间有限。未完待续。。。