2012-01-19 268 views
1

我正在創建一個必須檢索已知遠程文件並通過其瀏覽器將其返回給訪問者的ASP.NET(VB.NET)應用程序。我試圖使用位於此處的微軟樣本:http://support.microsoft.com/?kbid=812406,並且遇到錯誤「此流不支持查找操作」。我不知道如何繼續。將文件從FTP服務器下載到瀏覽器

以下是標有錯誤行的代碼。

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 

回答

0

不要打擾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 
+0

這就像一個魅力。非常感謝你! –

相關問題