2014-02-25 65 views
3
讀取文件名排序

我想閱讀被扔進一個列表文件夾和文件名排序,以顯示 比如我有一個看起來像這樣的文件:我怎樣的DirectoryInfo

1-4999 .TXT

5000-9999.txt ......

我想排序的數據文件夾

 var endpageNext = pagenumber * 100; 
     var startpageNext = endpageNext - (100 - 1); 

     var lst = GetFile(startpageNext, endpageNext); 

Picture Data Folder

Picture Visual Studio break point

 internal List<string> GetFile(int startpagenext, int endpagenext) 
    { 
     var dir = DataAccessSetting.CustomerSplit; 
     DirectoryInfo directoryInfo = new DirectoryInfo(dir); 
     var s = directoryInfo.GetFiles("*.txt"); 
     var lstfilename = new List<string>(); 
     foreach (var file in s) 
     { 
      var fileWithoutExtension = Path.GetFileNameWithoutExtension(file.Name); 
      var splitNameFile = fileWithoutExtension.Split('-'); 

      if ((startpagenext >= int.Parse(splitNameFile[0]) && startpagenext <= int.Parse(splitNameFile[1])) || (endpagenext >= int.Parse(splitNameFile[0]) && endpagenext <= int.Parse(splitNameFile[1]))) 
      { 
       var ppath = dir + fileWithoutExtension + ".txt"; 
       lstfilename.Add(ppath); 
      } 

     } 

     return lstfilename; 
    } 
+0

你怎麼稱呼這種方法,用什麼參數?參數startpagenext和endpagenext有什麼用處? – tafa

+0

我發現,根據編輯的問題 – alexis

回答

2

這應該工作:

List<string> lstfilename = System.IO.Directory 
    .EnumerateFiles(dir, "*.txt", System.IO.SearchOption.TopDirectoryOnly) 
    .Select(Path => new { 
     Path, 
     split = System.IO.Path.GetFileNameWithoutExtension(Path).Split('-') 
    }) 
    .Where(x => x.split.Length == 2 && x.split.All(s => s.All(Char.IsDigit))) 
    .Select(x => new { 
     x.Path, 
     Num1 = int.Parse(x.split[0]), 
     Num2 = int.Parse(x.split[1]), 
    }) 
    .Where(x => (startpagenext >= x.Num1 && startpagenext <= x.Num2) 
      || (endpagenext >= x.Num1 && endpagenext <= x.Num2)) 
    .OrderBy(x => x.Num1).ThenBy(x => x.Num2) 
    .Select(x => x.Path) 
    .ToList(); 
+0

非常非常好的用戶我的數量,計算出兩個變量的公式。 – alexis