C# sort files by name to hide traps and pay attention to problems(serial in file name)

Lionsure 2020-08-26 Original by the website

Generally speaking, files are sorted by name by default. When all files in a certain directory are got with C# or java, they are sorted by name. In most cases, no error will occur. If the file name contains a serial number, such as file 1, file 2, file 3, ..., file 9, file 10, file 11, ..., an error will occur when the files are got in a loop. The file got may not be the expected file.

First look at how the file names containing the serial number are sorted by name. Still using the above example, the file names are sorted as: file 1, file 10, file 11, file 2, file 3, ..., file 9, .... The "File 10, File 11" is arranged after "File 1" and before "File 2". I originally thought that the last file name was "File 11", but the result was wrong.

 

Example of C# sort files by name to hide traps:

If you get all the text files in a certain folder, some files have serial numbers in their file names, that is, "File 1, File 2, ..." above. The following code gets files first and then outputs the results sorted by name:

/// <summary>
       /// Example of C# sort files by name to hide traps
       /// </summary>
       /// <param name="filePath">Path</param>
       /// <returns>File name list</returns>

       private IList<string> GetFileNames(string filePath)
       {
              DirectoryInfo di = new DirectoryInfo(filePath);
              FileInfo[] fi = di.GetFiles("*.txt");
              IList<string> iFileName = new List<string>();
              for (int i = 0; i < fi.Length; i++)
              {
                     iFileName.Add(fi[i].Name);
              }
              return iFileName;
        }

Call:

string filePath = @"G:\Design\txtfile";
       IList<string> ifn = GetFileNames(filePath);
       for (int i = 0; i < ifn.Count; i++)
       {
              Response.Write("<br />" + ifn[i]);
       }

Output result:

File 1
       File 10
       File 11
       File 2
       File 3
       File 4
       File 5
       File 6
       File 7
       File 8
       File 9

If you take the last file name, such as ifn[ifn.Count - 1], it is expected that "file 11" should be got. According to the output result, "file 9" is got. This is a trap hidden by file name. It is easy ignore. Although it is an example of C#, the sorting of java file names should also pay attention to this problem.

If you want to use ifn[ifn.Count - 1] to get to the last file, you need to reorder the got files by time.