Foros del Web » Programando para Internet » ASP Clásico »

¿Es posible ordenar por fecha de creación?

Estas en el tema de ¿Es posible ordenar por fecha de creación? en el foro de ASP Clásico en Foros del Web. Tengo esta duda, necesito leer de una carpeta todos los archivos que ahí contenga, pero necesito que aparezcan del más reciente al menos reciente. Todo ...
  #1 (permalink)  
Antiguo 06/01/2003, 10:35
 
Fecha de Ingreso: noviembre-2002
Mensajes: 34
Antigüedad: 21 años, 6 meses
Puntos: 0
Pregunta ¿Es posible ordenar por fecha de creación?

Tengo esta duda, necesito leer de una carpeta todos los archivos que ahí contenga, pero necesito que aparezcan del más reciente al menos reciente.

Todo esto lo estoy haciendo con el File System Object, pero quisiera saber si hay una forma directa de ordenarlos por fecha
como si fueran de alguna tabla de Base de datos.

¿Sabe alguien si se puede?, se los agradecería mucho.

  #2 (permalink)  
Antiguo 06/01/2003, 14:13
Avatar de AlZuwaga
Colaborador
 
Fecha de Ingreso: febrero-2001
Ubicación: 34.517 S, 58.500 O
Mensajes: 14.550
Antigüedad: 23 años, 3 meses
Puntos: 535
Por el método de la burbuja:

Two-Dimensional Array Sort Using Bubble Sort


Acá lo intenté recrear utilizando FileSystemObject, pero tuve un par de problemas:

1- no pude crear el array dinámicamente. En realidad, no se como establecer dinámicamente la primer dimensión del array (vamos, la cantidad de archivos):

Dim arrDualArray(18,1)

18 es la cantidad de archivos que YO tengo en el root del servidor y no se por qué no me permite hacer esto...

Dim arrDualArray(Carpeta.Files.Count-1,1)

... siendo que Carpeta.Files.Count-1 es igual, en este caso, a 18



2- Al ser las fechas en formato DD/MM/AAAA HH:MM:SS, no ordenaba correctamente. Así que decidí pasarlas al formato AAAAMMDD para que veas cómo ordena al menos de manera numérica

Ahora si, el código:



<%
Set FSO = Server.CreateObject("Scripting.FileSystemObject")
Set Carpeta = FSO.GetFolder(Server.MapPath("/"))
Set ArchivosDelDir = Carpeta.Files

Cantidad = Carpeta.Files.Count-1
Response.Write "Cantidad de archivos: " & Cantidad & "<br><br>"

Dim arrDualArray(18,1)

j = 0
k = 0

For Each Archivo in ArchivosDelDir

arrDualArray(j,k) = Archivo.name
k = 1
arrDualArray(j,k) = Right(Left(Archivo.DateLastModified, 10), 4) & Mid(Left(Archivo.DateLastModified, 10), 4, 2) &

Left(Left(Archivo.DateLastModified, 10), 2)

k = 0
j = j + 1

Next


Response.Write "<b><u>Unsorted List of 2d Array:</u></b><br>"
For i = LBound(arrDualArray) to UBound(arrDualArray)
Response.Write arrDualArray(i, 0) & " - "
Response.Write arrDualArray(i, 1) & "<BR>"
Next

Sub DualSorter( byRef arrArray, DimensionToSort )
Dim row, j, StartingKeyValue, StartingOtherValue, _
NewStartingKey, NewStartingOther, _
swap_pos, OtherDimension
Const column = 1

' Ensure that the user has picked a valid DimensionToSort
If DimensionToSort = 1 then
OtherDimension = 0
ElseIf DimensionToSort = 0 then
OtherDimension = 1
Else
'Shoot, invalid value of DimensionToSort
Response.Write "Invalid dimension for DimensionToSort: " & _
"must be value of 1 or 0."
Response.End
End If

For row = 0 To UBound( arrArray, column ) - 1
'Start outer loop.

'Take a snapshot of the first element
'in the array because if there is a
'smaller value elsewhere in the array
'we'll need to do a swap.
StartingKeyValue = arrArray ( row, DimensionToSort )
StartingOtherValue = arrArray ( row, OtherDimension )

' Default the Starting values to the First Record
NewStartingKey = arrArray ( row, DimensionToSort )
NewStartingOther = arrArray ( row, OtherDimension )

swap_pos = row

For j = row + 1 to UBound( arrArray, column )
'Start inner loop.
If arrArray ( j, DimensionToSort ) < NewStartingKey Then
'This is now the lowest number -
'remember it's position.
swap_pos = j
NewStartingKey = arrArray ( j, DimensionToSort )
NewStartingOther = arrArray ( j, OtherDimension )
End If
Next

If swap_pos <> row Then
'If we get here then we are about to do a swap
'within the array.
arrArray ( swap_pos, DimensionToSort ) = StartingKeyValue
arrArray ( swap_pos, OtherDimension ) = StartingOtherValue

arrArray ( row, DimensionToSort ) = NewStartingKey
arrArray ( row, OtherDimension ) = NewStartingOther

End If
Next
End Sub

call DualSorter(arrDualArray, 1)

Response.Write "<p><b><u>Sorted List of 2d Array by Number:</u></b><br>"
For i = LBound(arrDualArray) to UBound(arrDualArray)
Response.Write arrDualArray(i, 0) & " - "
Response.Write arrDualArray(i, 1) & "<BR>"
Next

call DualSorter(arrDualArray, 0)

Response.Write "<p><b><u>Sorted List of 2d Array by Name:</u></b><br>"
For i = LBound(arrDualArray) to UBound(arrDualArray)
Response.Write arrDualArray(i, 0) & " - "
Response.Write arrDualArray(i, 1) & "<BR>"
Next
%>
  #3 (permalink)  
Antiguo 06/01/2003, 14:21
Avatar de bakanzipp  
Fecha de Ingreso: noviembre-2001
Ubicación: santiago de shilli
Mensajes: 2.554
Antigüedad: 22 años, 7 meses
Puntos: 0
vaya ensalada daz....te diste el tpo de sacarlo...

oye una duda...

esta funcion sirve?..te devuelve la cantidad o no?

response.write Carpeta.Files.Count-1
  #4 (permalink)  
Antiguo 06/01/2003, 14:52
Avatar de AlZuwaga
Colaborador
 
Fecha de Ingreso: febrero-2001
Ubicación: 34.517 S, 58.500 O
Mensajes: 14.550
Antigüedad: 23 años, 3 meses
Puntos: 535
Cita:
18 es la cantidad de archivos que YO tengo en el root del servidor...
Aish, es que me confundí
La cantidad de archivos es, en mi caso, 19.

Por lo que la línea correcta para ver la cantidad de archivos es:

Cantidad = Carpeta.Files.Count 'SIN EL -1

Pero para 19 archivos, está bien declarar el array así: Dim arrDualArray(18,1)


Mas esto no sirve (aunque devuelva 18):

Dim arrDualArray(Carpeta.Files.Count-1,1)

Este es el error que arroja:


Error de compilación de Microsoft VBScript error '800a0402'

Se esperaba una constante entera

/1.asp, line 9

Dim arrDualArray(Carpeta.Files.Count-1,1)
-----------------^





En fin... tanto brindis por las fiestas que pasaron me está haciendo mal
  #5 (permalink)  
Antiguo 06/01/2003, 15:27
Avatar de bakanzipp  
Fecha de Ingreso: noviembre-2001
Ubicación: santiago de shilli
Mensajes: 2.554
Antigüedad: 22 años, 7 meses
Puntos: 0
probaste haciendo esto?..

Cantidad = Carpeta.Files.Count -1

arreglo(cint(cantidad),1)


todavia no entiendo por ke no deja
  #6 (permalink)  
Antiguo 07/01/2003, 12:02
 
Fecha de Ingreso: noviembre-2002
Mensajes: 34
Antigüedad: 21 años, 6 meses
Puntos: 0
Gracias

Muchas gracias por el ejemplo, mientras tanto lo estaba realizando así:

<%
Dim fso, Carpeta, Fichero
Dim archivos(100)

'Creamos el objeto file system object
Set fso = Server.CreateObject("Scripting.FileSystemObject")

'Seleccionamos la carpeta donde se encuentra el archivo
Set Carpeta = fso.GetFolder("c:\My dir")


Dim num_dias(100)
Dim fechas(100)

For i = 0 to 100
num_dias(i) = 32
fechas(i) = "-"
archivos(i) = "-"
Next

fecha_actual = Now
i = 1
For Each Fichero in Carpeta.Files
fecha_creado = Fichero.DateCreated
dias = DateDiff("d",fecha_creado, fecha_actual)
if dias <= 31 then

num_dias(i) = dias
archivos(i) = fichero.name
fechas(i) = fecha_creado
i = i + 1
end if
Next
total = i


Dim j, k
Dim AuxA, AuxD, AuxF
For k = 1 to total-1
For j = 1 to total-k
if num_dias(j) > num_dias(j+1) then
AuxD = num_dias(j)
AuxA = archivos(j)
AuxF = fechas(j)
num_dias(j) = num_dias(j+1)
archivos(j) = archivos(j+1)
fechas(j) = fechas(j+1)
num_dias(j+1) = AuxD
archivos(j+1) = AuxA
fechas(j+1) = AuxF
end if
Next
Next


Es algo bastante primitivo pero me funcionó, de todas formas voy a probar el código que me dieron para ver cual se ejecuta más rápido.

Gracias
  #7 (permalink)  
Antiguo 29/07/2003, 17:03
 
Fecha de Ingreso: enero-2003
Ubicación: La Plata. Buenos Aires.
Mensajes: 9
Antigüedad: 21 años, 4 meses
Puntos: 0
Creo que es tarde pero por ahi les sirve...
Para definir un arreglo dinamicamente hay que usar el REDIM

Es decir, para el ejemplo hay que usar los siguiente

dim arrDualArray()
redim arrDualArray(Carpeta.Files.Count-1,1)

estas dos instrucciones te devuelven el vector de la dimension que necesites.
  #8 (permalink)  
Antiguo 30/07/2003, 04:52
Avatar de AlexNV  
Fecha de Ingreso: junio-2003
Ubicación: Madrid
Mensajes: 289
Antigüedad: 21 años
Puntos: 1
Otra forma es crearte un recordset, rellenarlo con los datos del filesystem y luego ordenarlo. Aquí tienes un ejemplo, que te muestra el nombre del fichero, el tamaño y la fecha y lo ordena por fecha descendentemente, pero lo puedes ordenar por el campo que quieras.

Código:
Dim objFSO
Dim objFolder
Dim strPath
Dim objItem

strPath = "./"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Server.MapPath(strPath))


dim cont
cont = 0
dim fecha
dim rs
Set rs = Server.CreateObject("ADODB.Recordset")

rs.Fields.Append "FileName", 8, 80
rs.Fields.Append "FileSize", 5
rs.Fields.Append "FileDate", 133

rs.Sort = "FileDate desc"
rs.Open

For Each objItem In objFolder.Files
		rs.addnew 
		rs.Fields("FileName").Value = objItem.Name
		rs.Fields("FileSize").Value = (objItem.Size/1024) + .5
		rs.Fields("FileDate").Value = cdate(objItem.DateLastModified)
		rs.Update
next

Set objItem = Nothing
Set objFolder = Nothing
Set objFSO = Nothing

response.write("<table border=0 width=80% bgcolor=white cellpadding=1 cellspacing=1>")

if not rs.eof then rs.movefirst
do while not rs.eof
		if cont = 0 then
			response.write("<tr bgcolor=#006699 >")
			response.write("<td colspan=2 align='center'><font color='white'>Nombre de fichero")
			response.write("<td align='center'><font color='white'>Tamaño")
			response.write("<td align='right'><font color='white'>Fecha")
			response.write("</tr>")
		end if
		response.write ("<tr>")
		response.write ("<td align='right'><img src='../imag/flecha2.gif' width=9 height=9>")
		response.write ("<td align='left'><a href='" & strpath & rs.fields("FileName").Value & "' border=0>" & rs.fields("FileName").Value  )
		response.write ("<td align='center'>" & Int(rs.fields("FileSize").Value ) &  " Kb")
		fecha = rs.fields("FileDate").Value 
		response.write ("<td align='right'>" & day(cdate(fecha)) & "/" & month(cdate(fecha)) & "/" & year(cdate(fecha)))
		'response.write ("<td>" & FormatDateTime(CDate(objItem.DateLastModified),0) )
		cont = cont + 1
		rs.MoveNext 
Loop
if cont=0 then
	response.write ("<td align='center'><font color=#006699>No existen ficheros disponibles</font>")
end if

response.write("</table>")
rs.close
set rs = nothing
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 15:13.