2012-03-13 149 views
2

我可能花了大約500個小時使用谷歌搜索和閱讀MSDN文檔,它仍然拒絕按我想要的方式工作。按名稱排序FileSystemInfo []

我可以通過名稱文件進行排序是這樣的:

01.png 
02.png 
03.png 
04.png 

即所有相同的文件長度。

第二個是有一個文件長度較長的文件一切都會到地獄。

例如順序:

1.png 
2.png 
3.png 
4.png 
5.png 
10.png 
11.png 

它讀取:

1.png, 2.png then 10.png, 11.png 

我不想這樣。

我的代碼:

DirectoryInfo di = new DirectoryInfo(directoryLoc); 
FileSystemInfo[] files = di.GetFileSystemInfos("*." + fileExtension); 
Array.Sort<FileSystemInfo>(files, new Comparison<FileSystemInfo>(compareFiles)); 

foreach (FileInfo fri in files) 
{ 
    fri.MoveTo(directoryLoc + "\\" + prefix + "{" + operationNumber.ToString() + "}" + (i - 1).ToString("D10") + 
     "." + fileExtension); 

    i--; 
    x++; 
    progressPB.Value = (x/fileCount) * 100; 
} 

// compare by file name 
int compareFiles(FileSystemInfo a, FileSystemInfo b) 
{ 
    // return a.LastWriteTime.CompareTo(b.LastWriteTime); 
    return a.Name.CompareTo(b.Name); 
} 
+0

是否可以在您的方案中更改文件名模式?例如。從1.png到01.png? – 2012-03-13 10:53:46

+1

試試這個http://stackoverflow.com/questions/1601834/c-implementation-of-or-alternative-to-strcmplogicalw-in-shlwapi-dll,'StrCmpLogicalW'是Windows API,它可以完成排序的「魔術」文件名以「邏輯」方式。 – xanatos 2012-03-13 11:00:05

回答

3

這不是文件長度特別的事情 - 這是名稱的問題在詞典順序進行比較。

這聽起來像是在這種特殊情況下,您希望獲取沒有擴展名的名稱,嘗試將其解析爲一個整數,然後將這兩個名稱進行比較 - 如果失敗,可以使用字典順序。

當然,如果您有「debug1.png,debug2.png,... debug10.png」,那麼這將不起作用......在這種情況下,您需要更復雜的算法。

0

您的代碼是正確的,並按預期工作,只是排序按字母順序執行,而不是數字。

例如,字符串「1」,「10」,「2」按字母順序排列。相反,如果你知道你的文件名總是隻是一個數字加「.png」,你可以按數字進行排序。舉例來說,這樣的事情:

int compareFiles(FileSystemInfo a, FileSystemInfo b)   
{    
    // Given an input 10.png, parses the filename as integer to return 10 
    int first = int.Parse(Path.GetFileNameWithoutExtension(a.Name)); 
    int second = int.Parse(Path.GetFileNameWithoutExtension(b.Name)); 

    // Performs the comparison on the integer part of the filename 
    return first.CompareTo(second); 
} 
3

你比較名稱作爲字符串,即使(我假設),你希望他們通過排序。

這是一個衆所周知的問題,其中「10」到來之前「9」,因爲10的第一個字符(1)小於第一個字符在9

如果你知道文件將所有由編號名稱組成,您可以修改自定義排序例程以將名稱轉換爲整數並對其進行適當的排序。

0

我遇到了同樣的問題,但我不是自己排序列表,而是使用6位'0'填充密鑰更改了文件名。

我的列表現在看起來是這樣的:

000001.jpg 
000002.jpg 
000003.jpg 
... 
000010.jpg 

但是,如果你不能改變文件名,你將不得不實現自己的排序例程來對付阿爾法排序。

0

linq和正則表達式來修復排序?

var orderedFileSysInfos = 
    new DirectoryInfo(directoryloc) 
    .GetFileSystemInfos("*." + fileExtension) 
    //regex below grabs the first bunch of consecutive digits in file name 
    //you might want something different 
    .Select(fsi => new{fsi, match = Regex.Match(fsi.Name, @"\d+")}) 
    //filter away names without digits 
    .Where(x => x.match.Success) 
    //parse the digits to int 
    .Select(x => new {x.fsi, order = int.Parse(x.match.Value)}) 
    //use this value to perform ordering 
    .OrderBy(x => x.order) 
    //select original FileSystemInfo 
    .Select(x => x.fsi) 
    //.ToArray() //maybe?