Foros del Web » Programación para mayores de 30 ;) » .NET »

Detectar Archivo para Descargar en VB.NET

Estas en el tema de Detectar Archivo para Descargar en VB.NET en el foro de .NET en Foros del Web. Tengo una aplicación en VB.NET. Me gustaría subir un archivo a mi hosting y que desde mi aplicación yo pueda validar si el archivo existe ...
  #1 (permalink)  
Antiguo 04/11/2014, 07:10
Avatar de RsOfT  
Fecha de Ingreso: marzo-2002
Ubicación: InterNET
Mensajes: 1.121
Antigüedad: 22 años, 1 mes
Puntos: 7
Detectar Archivo para Descargar en VB.NET

Tengo una aplicación en VB.NET. Me gustaría subir un archivo a mi hosting y que desde mi aplicación yo pueda validar si el archivo existe o está disponible para descargarlo.

Me gustaría preguntarle a la aplicación algo como esto:

Código:
If Archivo_Descargable("www.hosting.com\archivo.ZIP")=true Then
...
end if 
¿Alguien ha hecho algo parecido?
__________________
.::RsOfT::.
--El que se aferra a lo conocido, nunca conocerá lo desconocido--
--Es intentando lo imposible como se realiza lo posible--
--Es de pésimo gusto contentarse con algo mediocre cuando lo excelente está a nuestro alcance--
  #2 (permalink)  
Antiguo 05/11/2014, 12:25
 
Fecha de Ingreso: abril-2011
Mensajes: 1.342
Antigüedad: 13 años
Puntos: 344
Respuesta: Detectar Archivo para Descargar en VB.NET

Buenas,

Puedes crear una función que verifique eso:

Código vb:
Ver original
  1. Public Shared Function ExistsRemoteFile(remoteFilename As String) As Boolean
  2.  
  3.         Dim remoteStream As Stream = Nothing
  4.         Dim response As WebResponse = Nothing
  5.         Dim existFile As Boolean = False
  6.  
  7.         Try
  8.             ' Create a request for the specified remote file name
  9.            Dim request As WebRequest = WebRequest.Create(remoteFilename)
  10.             If request IsNot Nothing Then
  11.                 ' Send the request to the server and retrieve the
  12.                ' WebResponse object
  13.                response = request.GetResponse()
  14.                 If response IsNot Nothing Then
  15.                     ' Once the WebResponse object has been retrieved,
  16.                    ' get the stream object associated with the response's data
  17.                    remoteStream = response.GetResponseStream()
  18.                     existFile = remoteStream IsNot Nothing
  19.                 End If
  20.             End If
  21.         Catch ex As Exception
  22.             existFile = False
  23.         Finally
  24.             ' Close the response and streams objects here
  25.            ' to make sure they're closed even if an exception
  26.            ' is thrown at some point
  27.            If response IsNot Nothing Then
  28.                 response.Close()
  29.             End If
  30.             If remoteStream IsNot Nothing Then
  31.                 remoteStream.Close()
  32.             End If
  33.         End Try
  34.  
  35.         Return existFile
  36.  
  37.     End Function

Hay que tener en cuenta que no diferencia entre ficheros y páginas html, es decir, sólo te dice si una dirección web devuelve contenido, pero debería valerte.

Para descargar el fichero puedes usar la siguiente función (sacada de esta página: http://www.codeguru.com/columns/dotn...se-Classes.htm, la anterior función está basada en esta):

Código vb:
Ver original
  1. Public Shared Function DownloadFile(remoteFilename As [String], localFilename As [String]) As Integer
  2.         ' Function will return the number of bytes processed
  3.        ' to the caller. Initialize to 0 here.
  4.        Dim bytesProcessed As Integer = 0
  5.  
  6.         ' Assign values to these objects here so that they can
  7.        ' be referenced in the finally block
  8.        Dim remoteStream As Stream = Nothing
  9.         Dim localStream As Stream = Nothing
  10.         Dim response As WebResponse = Nothing
  11.  
  12.         ' Use a try/catch/finally block as both the WebRequest and Stream
  13.        ' classes throw exceptions upon error
  14.        Try
  15.             ' Create a request for the specified remote file name
  16.            Dim request As WebRequest = WebRequest.Create(remoteFilename)
  17.             If request IsNot Nothing Then
  18.                 ' Send the request to the server and retrieve the
  19.                ' WebResponse object
  20.                response = request.GetResponse()
  21.                 If response IsNot Nothing Then
  22.                     ' Once the WebResponse object has been retrieved,
  23.                    ' get the stream object associated with the response's data
  24.                    remoteStream = response.GetResponseStream()
  25.  
  26.                     ' Create the local file
  27.                    localStream = File.Create(localFilename)
  28.  
  29.                     ' Allocate a 1k buffer
  30.                    Dim buffer As Byte() = New Byte(1023) {}
  31.                     Dim bytesRead As Integer
  32.  
  33.                     ' Simple do/while loop to read from stream until
  34.                    ' no bytes are returned
  35.                    Do
  36.                         ' Read data (up to 1k) from the stream
  37.                        bytesRead = remoteStream.Read(buffer, 0, buffer.Length)
  38.  
  39.                         ' Write the data to the local file
  40.                        localStream.Write(buffer, 0, bytesRead)
  41.  
  42.                         ' Increment total bytes processed
  43.                        bytesProcessed += bytesRead
  44.                     Loop While bytesRead > 0
  45.                 End If
  46.             End If
  47.         Catch e As Exception
  48.             Console.WriteLine(e.Message)
  49.         Finally
  50.             ' Close the response and streams objects here
  51.            ' to make sure they're closed even if an exception
  52.            ' is thrown at some point
  53.            If response IsNot Nothing Then
  54.                 response.Close()
  55.             End If
  56.             If remoteStream IsNot Nothing Then
  57.                 remoteStream.Close()
  58.             End If
  59.             If localStream IsNot Nothing Then
  60.                 localStream.Close()
  61.             End If
  62.         End Try
  63.  
  64.         ' Return total bytes processed to caller.
  65.        Return bytesProcessed
  66.     End Function

Un saludo.
  #3 (permalink)  
Antiguo 07/11/2014, 07:25
Avatar de RsOfT  
Fecha de Ingreso: marzo-2002
Ubicación: InterNET
Mensajes: 1.121
Antigüedad: 22 años, 1 mes
Puntos: 7
Respuesta: Detectar Archivo para Descargar en VB.NET

Gracias alexg88.

Hice la prueba con la función "ExistsRemoteFile" y aunque el archivo no exista, siempre me devuelve TRUE.

Probé con http://www.sj.com.do/Download/Actual...es/Lugares.rar y a la misma URL se agregé una S para que sea fictisia (http://www.sj.com.do/Download/Actual...s/LugaresS.rar).

También probé la función DownloadFile. Cuando pongo la URL que no existe, como quiera me descarga un archivo.

Ej.:
Código:
Call DownloadFile("http://www.sj.com.do/Download/Actualizaciones/LugaresS.rar", "LugaresS.rar")
__________________
.::RsOfT::.
--El que se aferra a lo conocido, nunca conocerá lo desconocido--
--Es intentando lo imposible como se realiza lo posible--
--Es de pésimo gusto contentarse con algo mediocre cuando lo excelente está a nuestro alcance--

Etiquetas: net
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:23.