终于找到ASP.NET c# 简单的获取远端文件的方法!

本文介绍了一种使用C#编写的精简代码来实现从指定URL下载文件并保存到本地服务器的功能。该方法通过WebRequest和WebResponse进行HTTP请求与响应处理,并利用BinaryReader读取二进制流,最后将文件内容写入到指定路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

真的是找的很辛苦!先是看InernetOpen函数用法和示例,不行,然后又找C#写FTP客户端的方法,太烦琐,我其实只要一点点功能,找到某一个URL的文件,然后下载到本WEB Server指定目录。

终于在一个地方找到一个非常非常精简的代码,简直是太棒了!这样我可以实现在线更新法律法规了!

就一个函数,如下:

None.gif private   void  BT_Update_Click( object  sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif {
InBlock.gif   
string slocal = Server.MapPath("."+ "\\test.mdb";
InBlock.gif   GetHttpFile(
"http://www.jinwensoft.com/demo/database/lawdoc.mdb", slocal);
ExpandedBlockEnd.gif  }

None.gif
None.gif  
public   bool  GetHttpFile( string  sUrl, string  sSavePath)
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif {
InBlock.gif
InBlock.gif   
bool bRslt=false;
InBlock.gif
InBlock.gif   WebResponse oWebRps
=null;
InBlock.gif
InBlock.gif   WebRequest oWebRqst
=WebRequest.Create(sUrl);
InBlock.gif
InBlock.gif   oWebRqst.Timeout
=50000;
InBlock.gif
InBlock.gif   oWebRps
=oWebRqst.GetResponse();
InBlock.gif
InBlock.gif   
if(oWebRps!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif
InBlock.gif    BinaryReader oBnyRd
=new BinaryReader(oWebRps.GetResponseStream(),System.Text.Encoding.GetEncoding("GB2312"));
InBlock.gif 
InBlock.gif    
int iLen=Convert.ToInt32(oWebRps.ContentLength);
InBlock.gif  
InBlock.gif    FileStream oFileStream;
InBlock.gif
InBlock.gif   
InBlock.gif    
if(File.Exists(Request.MapPath("RecievedData.tmp")))
InBlock.gif     oFileStream
=File.OpenWrite(sSavePath);
InBlock.gif    
else
InBlock.gif     oFileStream
=File.Create(sSavePath);
InBlock.gif
InBlock.gif    oFileStream.SetLength((Int64)iLen);
InBlock.gif
InBlock.gif    oFileStream.Write(oBnyRd.ReadBytes(iLen),
0,iLen);
InBlock.gif
InBlock.gif    oFileStream.Close();
ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif   
return bRslt;
ExpandedBlockEnd.gif  }

None.gif

转载于:https://www.cnblogs.com/shfranklee/archive/2006/01/18/319900.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值