Загрузка файла с ftp-сервера в браузер - PullRequest
1 голос
/ 19 января 2012

Я создаю приложение 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

1 Ответ

0 голосов
/ 19 января 2012

Не беспокойтесь о 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 
...