• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
JensonBin
博客园    首页    新随笔    联系   管理    订阅  订阅

Asp.Net获取远程数据并保存为文件的简单代码

<%@Page Language="C#" Debug="true"%>
<%@Import NameSpace="System.Net"%>
<%@Import NameSpace="System.IO"%>
<script language="C#" runat="Server">
string sException=null;
public bool GetHttpFile(string sUrl,string sSavePath){
        bool bRslt=false;
        WebResponse oWebRps=null;
        WebRequest oWebRqst=WebRequest.Create(sUrl);
        oWebRqst.Timeout=50000;
        try{
                oWebRps=oWebRqst.GetResponse();
        }
        catch(WebException e){
                sException=e.Message.ToString();
        }
        catch(Exception e){
                sException=e.ToString();
        }
        finally{
                if(oWebRps!=null){
                        BinaryReader oBnyRd=new BinaryReader(oWebRps.GetResponseStream(),System.Text.Encoding.GetEncoding("GB2312"));
                        int iLen=Convert.ToInt32(oWebRps.ContentLength);
                        FileStream oFileStream;
                        try{
                                if(File.Exists(Request.MapPath("RecievedData.tmp"))){
                                        oFileStream=File.OpenWrite(sSavePath);
                                }
                                else{
                                        oFileStream=File.Create(sSavePath);
                                }
                                oFileStream.SetLength((Int64)iLen);
                                oFileStream.Write(oBnyRd.ReadBytes(iLen),0,iLen);
                                oFileStream.Close();
                        }
                        finally{
                                oBnyRd.Close();
                                oWebRps.Close();
                        }
                        bRslt=true;
                }
        }
        return bRslt;
}
</script>
<%
TimeSpan oStartTime=DateTime.Now.TimeOfDay;
Response.Write(GetHttpFile("http://www.spbdev.com/download/DotNetInfo1.0.rar",Request.MapPath("RecievedFile.rar")));
Response.Write("<br><br>\r\n执行时间:" + DateTime.Now.TimeOfDay.Subtract(oStartTime).TotalMilliseconds.ToString() + " 毫秒");
%>
posted @ 2011-03-18 16:00  JensonBin  阅读(492)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3