【问题标题】:Downloading a file from an ftp server to the browser从 ftp 服务器下载文件到浏览器
【发布时间】:2012-01-19 18:12:10
【问题描述】:

我正在创建一个 ASP.NET (VB.NET) 应用程序,该应用程序必须检索已知的远程文件并通过浏览器将其返回给访问者。我正在尝试使用位于此处的 Microsoft 示例:http://support.microsoft.com/?kbid=812406 并遇到错误“此流不支持查找操作”。我不确定如何继续。

这是标有错误行的代码。

Dim ftpWebReq As Net.FtpWebRequest = CType(Net.WebRequest.Create(path), Net.FtpWebRequest)
ftpWebReq.Method = Net.WebRequestMethods.Ftp.DownloadFile
ftpWebReq.KeepAlive = False
ftpWebReq.UsePassive = False
ftpWebReq.Credentials = New Net.NetworkCredential(System.Web.Configuration.WebConfigurationManager.AppSettings("FtpId"), System.Web.Configuration.WebConfigurationManager.AppSettings("FtpPwd"))
Dim ftpWebResp As Net.FtpWebResponse = CType(ftpWebReq.GetResponse(), Net.FtpWebResponse)
Dim streamer As Stream = ftpWebResp.GetResponseStream()

Dim buffer(10000) As Byte   ' Buffer to read 10K bytes in chunk:
Dim length As Integer       ' Length of the file:
Dim dataToRead As Long      ' Total bytes to read:
dataToRead = streamer.Length    ' *** This is the error line ***
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=foo.txt")
While dataToRead > 0    ' Read the bytes.
If Response.IsClientConnected Then    ' Verify that the client is connected.
   length = streamer.Read(buffer, 0, 10000) ' Read the data in buffer
   Response.OutputStream.Write(buffer, 0, length)  ' Write the data to the current output stream.
   Response.Flush()        ' Flush the data to the HTML output.
   ReDim buffer(10000) ' Clear the buffer
   dataToRead = dataToRead - length
Else
   dataToRead = -1 'prevent infinite loop if user disconnects
End If
End While

【问题讨论】:

    标签: asp.net vb.net ftpwebrequest


    【解决方案1】:

    不要打扰dataToRead。继续阅读直到 length 为 0(即 streamer.Read() 返回 0)。这意味着您已到达信息流的末尾。

    我的 VB 有点生疏了,但我认为循环应该是这样的:

    finished = False
    While Not finished    ' Read the bytes.
        If Response.IsClientConnected Then    ' Verify that the client is connected.
            length = streamer.Read(buffer, 0, 10000) ' Read the data in buffer
            If length > 0 Then
                Response.OutputStream.Write(buffer, 0, length)  ' Write the data to the current output stream.
                Response.Flush()        ' Flush the data to the HTML output.
                ReDim buffer(10000) ' Clear the buffer
            Else
                finished = True
            End If
        Else
            finished = True
        End If
    End While 
    

    【讨论】: