在.NET中下载文件的一些方法

时间:2006/6/3 18:57:36      阅读:6938          

      最近总结了在.NET中下载文件的一些方法,大家可按自己的须要选择,第一种是利用XMLHTTP下载文件,先添加引用-COM-Microsoft Xml 3.0,然后在代码开始处写:Imports MSXML2

下面就是方法一的主要代码:

 1Private  Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)    
 2    Dim Url As String =  "http://www.web3.cn/images/logo1.gif" 
 3    Dim StringFileName As String =  Url.Substring(Url.LastIndexOf("/") + 1) 
 4    Dim StringFilePath As String =  Request.PhysicalApplicationPath 
 5    If Not StringFilePath.EndsWith("/") Then
 6         StringFilePath += "/"
 7    End If
 8    Dim _xmlhttp As MSXML2.XMLHTTP =  New MSXML2.XMLHTTPClass() 
 9    _xmlhttp.open("GET",Url,False,Nothing,Nothing)
10    _xmlhttp.send("")
11    If _xmlhttp.readyState = 4 Then
12        If System.IO.File.Exists(StringFilePath + StringFileName) Then
13            System.IO.File.Delete(StringFilePath + StringFileName)
14        End If
15        Dim fs As System.IO.FileStream =  New System.IO.FileStream(StringFilePath + StringFileName,System.IO.FileMode.CreateNew) 
16        Dim w As System.IO.BinaryWriter =  New System.IO.BinaryWriter(fs) 
17        w.Write(CType(_xmlhttp.responseBody, Byte()))
18        w.Close()
19        fs.Close()
20        Response.Write ("文件已经得到。<br><a href='" + Request.ApplicationPath + StringFileName +"' target='_blank'>")
21        Response.Write ("查看" + StringFileName + "</a>")
22    Else 
23    Response.Write (_xmlhttp.statusText)
24    End If
25    Response.End()
26End Sub

第二种方法是通过引入Imports System.IO

以下是代码:

 1Dim ImageSize As Long
 2Dim ImageBuffer() As Byte
 3
 4'文件名
 5Dim sfilename As String = System.Web.HttpUtility.UrlDecode("www_web3_cn_file.rar")
 6'文件存放路径(还原经过混淆的字符串)
 7Dim sPath As String = Server.MapPath("c:\down")
 8
 9ImageSize = FileLen(sPath) '设置文件大小
10'创建一文件流对象
11Dim fs As FileStream = New FileStream(sPath, FileMode.OpenOrCreate)
12
13'基于文件流创建二进制读
14Dim r As BinaryReader = New BinaryReader(fs)
15
16'指到文件的开头位置
17r.BaseStream.Seek(0, SeekOrigin.Begin)
18ImageBuffer = r.ReadBytes(ImageSize)
19
20sfilename = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Right(sfilename, 18)))
21
22Response.Clear()
23Response.ContentType = "text/html"
24Response.AddHeader("Content-Disposition", "attachment;filename=" & sfilename)
25Response.BinaryWrite(ImageBuffer)
26fs.Close()

一点提醒:如果文件是中文名字最好经过编码。

评论
  • Re:在.NET中下载文件的一些方法  (2006/6/12 10:36:28) by 王丹 
    感谢分享
  • Re:在.NET中下载文件的一些方法  (2006/8/4 16:36:07) by 飘萍 
    防止别人得到绝对地址。
标 题:
 
姓 名:
 
主 页:

验证码:

评论:
 

Because of the cache,you may see your comments several minutes later.