Ordenar el Directorio.GetFiles()
System.IO.Directory.GetFiles()
devuelve un string[]
. ¿Cuál es el orden de clasificación predeterminado para los valores devueltos? Estoy asumiendo por nombre, pero si es así, ¿cuánto lo afecta la cultura actual? ¿Puedes cambiarlo a algo como la fecha de creación?
Actualización: MSDN señala que el orden de clasificación no está garantizado para.Net 3.5, pero la versión 2.0 de la página no dice nada en absoluto y ninguna de las páginas le ayudará a ordenar por cosas como el tiempo de creación o modificación. Esa información se pierde una vez que tiene el array (solo contiene cadenas). Podría construir un comparador que verificaría cada archivo que obtiene ,pero eso significa acceder al sistema de archivos repetidamente cuando presumiblemente el.El método GetFiles () ya hace esto. Parece muy ineficiente.
13 answers
Si está interesado en las propiedades de los archivos como CreationTime, entonces tendría más sentido usar System.IO.DirectoryInfo.GetFileSystemInfos(). A continuación, puede ordenar estos utilizando uno de los métodos de extensión en el sistema.Linq, por ejemplo:
DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);
Edit - lo siento, no me di cuenta de la etiqueta .NET2.0, así que ignora la clasificación LINQ. Sin embargo, la sugerencia de usar System.IO.DirectoryInfo.GetFileSystemInfos() todavía se mantiene.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-13 22:22:30
En.NET 2.0, necesitará usar Array.Sort para ordenar el sistema de archivos.
Además, puede usar un delegado Comparador para evitar tener que declarar una clase solo para la comparación:
DirectoryInfo dir = new DirectoryInfo(path);
FileSystemInfo[] files = dir.GetFileSystemInfos();
// sort them by creation time
Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b)
{
return a.LastWriteTime.CompareTo(b.LastWriteTime);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-10 20:57:43
Aquí está el VB.Net solución que he usado.
Primero haga una clase para comparar fechas:
Private Class DateComparer
Implements System.Collections.IComparer
Public Function Compare(ByVal info1 As Object, ByVal info2 As Object) As Integer Implements System.Collections.IComparer.Compare
Dim FileInfo1 As System.IO.FileInfo = DirectCast(info1, System.IO.FileInfo)
Dim FileInfo2 As System.IO.FileInfo = DirectCast(info2, System.IO.FileInfo)
Dim Date1 As DateTime = FileInfo1.CreationTime
Dim Date2 As DateTime = FileInfo2.CreationTime
If Date1 > Date2 Then Return 1
If Date1 < Date2 Then Return -1
Return 0
End Function
End Class
Luego use el comparador mientras ordena la matriz:
Dim DirectoryInfo As New System.IO.DirectoryInfo("C:\")
Dim Files() As System.IO.FileInfo = DirectoryInfo.GetFiles()
Dim comparer As IComparer = New DateComparer()
Array.Sort(Files, comparer)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-02 10:24:05
Dim Files() As String
Files = System.IO.Directory.GetFiles("C:\")
Array.Sort(Files)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-28 11:49:56
De msdn:
El orden de los nombres de archivo devueltos no está garantizado; use el método Sort() si se requiere un orden de clasificación específico.
El método Sort() es el Array estándar.Sort (), que incluye IComparables (entre otras sobrecargas), por lo que si ordena por fecha de creación, se encargará de la localización en función de la configuración de la máquina.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 20:36:38
Puede implementar IComparer personalizado para ordenar. Lea la información del archivo para los archivos y compare como usted tiene gusto.
IComparer comparer = new YourCustomComparer();
Array.Sort(System.IO.Directory.GetFiles(), comparer);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 20:45:30
Un texto más sucinto VB.Net version...is muy bonito. Agradecer. Para recorrer la lista en orden inverso, agregue el método inverso...
For Each fi As IO.FileInfo In filePaths.reverse
' Do whatever you wish here
Next
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-12 16:14:52
La Documentación de MSDN indica que no hay garantía de ningún orden en los valores devueltos. Tienes que usar el método Sort ().
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 20:37:56
Tienes razón, el valor predeterminado es mi nombre asc. La única manera que he encontrado para cambiar el orden es crear una datatable de la colección FileInfo.
A continuación, puede utilizar el defaultView de la datatable y ordenar el directorio con el .Método de ordenación.
Esto es bastante complicado y bastante lento, pero espero que alguien publique una mejor solución.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 20:38:22
Puede escribir una interfaz IComparer personalizada para ordenar por fecha de creación, y luego pasarla a Array.Tipo. Probablemente también quiera ver StrCmpLogical, que es lo que se usa para hacer que el Explorador de ordenación use (ordenar números correctamente con texto).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 20:41:17
Si desea ordenar por algo como fecha de creación, probablemente necesite usar DirectoryInfo.GetFiles y luego ordenar la matriz resultante utilizando un Predicado adecuado.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 20:42:13
Solo una idea. Me gusta encontrar una salida fácil e intentar reutilizar los recursos ya disponibles. si tuviera que ordenar los archivos que habría creado un proceso y hacer syscal a " DIR [x:\Folders\SubFolders*.* ] /s /b /on" y captura la salida.
Con el comando DIR del sistema puede ordenar por:
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
The /S switch includes sub folders
NO ESTOY SEGURO SI D = By Date/Time está usando lastModifiedDate o FileCreateDate. Pero si el orden de clasificación necesario ya está incorporado en el comando DIR, lo obtendré llamando a syscall. Y ES RÁPIDO. Soy solo el tipo perezoso;)
Después de un poco de googlear encontré cambiar a ordenar por fecha/hora en particular:-
/t [[:]TimeField] : Specifies which time field to display or use for sorting. The following list describes each of the values you can use for TimeField.
Value Description
c : Creation
a : Last access
w : Last written
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-31 17:43:03
Un texto más sucinto VB.Net versión, si alguien está interesado
Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _
New DirectoryInfo("c:\temp").GetFiles() _
.OrderBy(Function(f As FileInfo) f.CreationTime)
For Each fi As IO.FileInfo In filePaths
' Do whatever you wish here
Next
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-21 13:22:11