Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c# - How to add files into List based on filename

I have files in a directory. I want to add each file to the list based on the filename in the loop. first need to sort based on code then value.

filename sample

   name|code|value|dept
   --------------------
   a_001_200_x.txt 
   ab_001_100_x.txt
   abc_003_100_x.txt
   abcd_002_100_x.txt

output should be

   a_001_100_x.txt
   ab_001_200_x.txt
   abc_002_100_x.txt
   abcd_003_100_x.txt
public void GetFiles()
{
     List<string> files =  Directory.GetFiles("C:/temp", "*.txt").ToList();
     foreach (var file in files)
    {
       Console.WriteLine(Path.GetFileName(file));
    }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the sample code for you. Steps will be read filespaths then getonly filenames from filepaths. Then add them in the list. Orderby list by filename. Then read actual files with already order filepath. Hope this is clear. Let me know if you have any questions.

    //string[] filePaths = Directory.GetFiles("Directory Path");
    string[] filePaths = new string[] { "a_001_200_x.txt", "ab_001_100_x.txt" };
    List<FileInput> fileInput = new List<FileInput>();
    foreach (string path in filePaths)
    {
        fileInput.Add(new FileInput
        {
           //here you can do Path.GetFileName(path).Substring(path.Length - 13, 13)
            FileName = path.Substring(path.Length - 13, 13),
            FilePath = path,
        });
    }

    fileInput = fileInput.OrderBy(x => x.FileName).ToList();

    foreach(var f in fileInput){
         //Read your file here from the disk with sorted order.
    }



public class FileInput
{
    public string FileName { get; set; }
    public string FilePath { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...