Katalog Sortujący.GetFiles()

System.IO.Directory.GetFiles() zwraca string[]. Jaka jest domyślna kolejność sortowania zwracanych wartości? Zakładam z nazwy, ale jeśli tak, to na ile wpływ ma obecna kultura? Możesz to zmienić na coś w rodzaju daty utworzenia?

Update: MSDN wskazuje, że kolejność sortowania nie jest gwarantowana dla. Net 3.5, ale Wersja 2.0 strony nic nie mówi i żadna strona nie pomoże Ci sortować według rzeczy, takich jak czas utworzenia lub modyfikacji. Ta informacja jest utracona, gdy masz tablica (zawiera tylko łańcuchy). Mógłbym zbudować porównywarkę, która sprawdzałaby każdy plik, który dostaje, ale oznacza to wielokrotne uzyskiwanie dostępu do systemu plików, gdy przypuszczalnie .Metoda GetFiles () już to robi. Wydaje się bardzo nieefektywne.

Author: casperOne, 2008-09-10

13 answers

Jeśli interesują Cię właściwości plików, takie jak CreationTime, wtedy bardziej sensowne byłoby użycie System. IO. DirectoryInfo. GetFileSystemInfos (). Następnie można je sortować za pomocą jednej z metod rozszerzenia w systemie.Linq, np.:

DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);

Edit-sorry, nie zauważyłem tagu. NET2. 0 więc zignoruj sortowanie LINQ. Sugestia użycia System. IO. DirectoryInfo. GetFileSystemInfos () nadal jednak istnieje.

 103
Author: Ian Nelson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-13 22:22:30

W. NET 2.0, musisz użyć tablicy.Sort aby posortować System FileSystemInfos.

Dodatkowo możesz użyć delegata porównującego, aby uniknąć konieczności deklarowania klasy tylko dla porównania:

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);
                                    });
 12
Author: Chris Karcher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-11-10 20:57:43

Oto VB.Net rozwiązanie, którego użyłem.

Najpierw zrób klasę, aby porównać daty:

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

Następnie użyj komparatora podczas sortowania tablicy:

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)
 12
Author: sebastiaan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-02 10:24:05

Dim Files() As String
Files = System.IO.Directory.GetFiles("C:\")
Array.Sort(Files)
 7
Author: Kibbee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-28 11:49:56

From msdn :

Kolejność zwracanych nazw plików nie jest gwarantowana; użyj metody Sort (), jeśli wymagana jest określona kolejność sortowania.

Metoda Sort() jest standardową tablicą.Sort (), która zajmuje IComparables (między innymi przeciążenia), więc jeśli sortujesz według daty utworzenia, zajmie się lokalizacją na podstawie ustawień maszyny.

 6
Author: Guy Starbuck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-09 20:36:38

Możesz zaimplementować Niestandardowy iComparer do sortowania. Przeczytaj informacje o plikach i porównaj, jak chcesz.

IComparer comparer = new YourCustomComparer();
Array.Sort(System.IO.Directory.GetFiles(), comparer);

Msdn info IComparer interface

 3
Author: Vertigo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-09 20:45:30

Bardziej zwięzły VB.Net version...is bardzo ładnie. Dziękuję. Aby przejść listę w odwrotnej kolejności, Dodaj metodę odwrotną...

For Each fi As IO.FileInfo In filePaths.reverse
  ' Do whatever you wish here
Next
 3
Author: skeltech,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-12 16:14:52

Dokumentacja MSDN stwierdza, że nie ma żadnej gwarancji kolejności zwracanych wartości. Musisz użyć metody Sort ().

 2
Author: Vaibhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-09 20:37:56

Masz rację, domyślnym jest moje imię asc. Jedynym sposobem, jaki znalazłem, aby zmienić kolejność sortowania, aby utworzyć datatable z kolekcji FileInfo.

Można następnie użyć DefaultView z datatable i posortować katalog z .Metoda sortowania.

To dość wciągające i dość powolne, ale mam nadzieję, że ktoś zamieści lepsze rozwiązanie.

 2
Author: GateKiller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-09 20:38:22

Możesz napisać niestandardowy interfejs IComparer do sortowania według daty utworzenia, a następnie przekazać go do tablicy.Sortuj. Prawdopodobnie chcesz również spojrzeć na StrCmpLogical, czyli to, co jest używane do sortowania Explorer używa (sortowanie liczb poprawnie z tekstem).

 2
Author: Tina Marie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-09 20:41:17

Jeśli chcesz sortować według daty utworzenia, prawdopodobnie musisz użyć DirectoryInfo.GetFiles, a następnie posortować wynikową tablicę używając odpowiedniego predykatu.

 2
Author: samjudson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-09 20:42:13

To tylko pomysł. Lubię znaleźć łatwe wyjście i spróbować ponownie wykorzystać już dostępne zasoby. gdybym miał sortować pliki, stworzyłbym proces i zrobił syscal do " DIR [x:\Folders\SubFolders*.* ] /S / B / on " i przechwycić wyjście.

Poleceniem systemowym DIR można sortować według:

/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

Nie jestem pewien, czy D = By Date / Time używa LastModifiedDate lub FileCreateDate. Ale jeśli potrzebny porządek sortowania jest już wbudowany w poleceniu DIR, uzyskam to przez wywołanie syscall. I to szybko. Jestem tylko leniwym facetem;)

po odrobinie googlowania znalazłem przełącznik do sortowania według konkretnej daty/godziny:-

/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
 1
Author: Mehdi Anis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-31 17:43:03

Bardziej zwięzły VB.Net Wersja, jeśli ktoś jest zainteresowany

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
 1
Author: Simon Molloy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-21 13:22:11