none
Pick 25 files in alphanumeric order from a folder RRS feed

  • Question

  • Hi, my requirement is I need to pick only 25 files from a folder which may have over 500 files.

    When the process is triggered, the number'ed files needs to be picked first then alphabets.

    With below code, it is triggering but not able to pick only those ordered 25 files, All  files are getting picked.

    Please advise what am I doing wrong ?

    string sourceFile = @"path\"; 
                var directory = new DirectoryInfo(sourceFile);
    
                var files = directory.GetFiles()
                    .Where(x => x.Name.EndsWith(".pdf"))
                     .OrderBy(x => x.GetName)
                     .Take(25).ToList();
    
    
                foreach (FileInfo file in files)
                {
                    string extention = System.IO.Path.GetExtension(file.Name); 
                    System.IO.File.Move(sourceFile + file.Name, sourceFile + file.Name.Replace(extention,".txt"));
                }


    Reason101

    Saturday, March 28, 2020 8:42 AM

All replies


  • string sourceFile = @"path\"; 
                var directory = new DirectoryInfo(sourceFile);
    
                var files = directory.GetFiles()
                    .Where(x => x.Name.EndsWith(".pdf"))
                     .OrderBy(x => x.GetName)
                     .Take(25).ToList();
    
    


    What is GetName here?

    Why aren't you using:

    .OrderBy(x => x.Name)

    - Wayne

    Saturday, March 28, 2020 10:27 AM
  • Hi Wayne, I copied pasted so it was a typo. I used x.Name only . Still facing issues

    Reason101

    Saturday, March 28, 2020 2:41 PM

  • With below code, it is triggering but not able to pick only those ordered 25 files, All  files are getting picked.


    There is no obvious reason why the selection code you posted should return
    ALL files instead of just 25. What do you see on the console when you build
    and run this example?

    static void Main(string[] args)
    {
        string sourceFile = @"path\";
        var directory = new DirectoryInfo(sourceFile);
    
        var files = directory.GetFiles()
            .Where(x => x.Name.EndsWith(".pdf"))
             .OrderBy(x => x.Name)
             .Take(25).ToList();
    
        int n = 1;
        foreach (FileInfo file in files)
        {
            Console.WriteLine("{0,2}==> {1}", n++, file);
        }
        Console.ReadLine();
    }
    

    - Wayne

    Saturday, March 28, 2020 9:53 PM
  • Say if first .pdf file name is a1.pdf. Well after renaming the first file to .txt it is going back to for loop, and then throwing the error 'a1.pdf' file doesnt exist. File not found. Not sure why it is in 2nd time of the loop still looking for the first file.

    Reason101

    Saturday, March 28, 2020 10:04 PM
  • Say if first .pdf file name is a1.pdf. Well after renaming the first file to .txt it is going back to for loop, and then throwing the error 'a1.pdf' file doesnt exist. File not found. Not sure why it is in 2nd time of the loop still looking for the first file.


    You didn't answer my question in my last post. If you're going to ignore our
    questions, we will ignore yours.

    For this *changed* symptom, you need to show the *exact* code you are using NOW.

    One thing you can try is to use a traditional for() loop instead of a foreach.

    Example change to my earlier sample:

    for(int x = 0; x < files.Count; ++x)
    {
        Console.WriteLine("{0,2}==> {1}", n++, files[x]);
    }
    

    - Wayne

    Saturday, March 28, 2020 11:17 PM
  • Well I tried with your provided foreach loop, and it is looping individually through each file.

    But after reading each file name, it should replace the extension and move to another file and so on until 25 sorted file. How should I place that code in for loop ?

    please see below is the console and the error I am receiving.

    As per you provided code above, if I use just for loop, then how will that be going to change my extension ? My requirement is out of 500 files in a folder, it should sort first by alphanumeric, and then just change 25 files accordingly. But this below code is behaving weird.


    • Edited by Reason101 Sunday, March 29, 2020 12:08 AM a
    Saturday, March 28, 2020 11:45 PM

  • As per you provided code above, if I use just for loop, then how will that be going to change my extension ?

    What are you talking about? The example of a for() loop I posted was meant as a 
    replacement for the foreach IN MY FIRST EXAMPLE. The purpose of that example 
    was to show in a stand-alone program that the selection code you are using does 
    in fact select the first 25 filenames, NOT *all* names as you claimed in your 
    original post.

    You are expected to alter *YOUR* code in the same way to use a for() loop.

    Stop looking for complete drop-in fixes for your code and do some serious 
    independent debugging.

    - Wayne

    Sunday, March 29, 2020 12:21 AM
  • I dont think you understood my question/requirement clearly. You are just answering randomly 



    • Edited by Reason101 Sunday, March 29, 2020 12:53 AM a
    Sunday, March 29, 2020 12:42 AM
  • if you provide partial code, that isn't going to help.

    Provide complete solution as per the requirement I asked please


    We haven't negotiated the price for contract programming services yet.
    If you're unhappy with the service provided so far, we will gladly
    refund the full amount that you've paid.

    In the interim, you get what *free* suggestions WE choose to offer.
    Not what you demand.

    - Wayne

    Sunday, March 29, 2020 12:53 AM
  • Make sure you're not modifying the collection while using foreach loop. It is a very common mistake and may lead to weird results. E.g. your collection should remain unchanged. Perhaps after you got your files, you can add them into a separate list just in case.

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Sunday, March 29, 2020 2:53 AM
    Moderator
  • Hi Naomi, thanks for your response. Below is my code.

    Actually it is renaming first file and then when 2nd time it is looping it is again for some weird reason saying first file name not found

     try
    
                {
                    string sourceFile = @"C:\UnitTest\";
                    var directory = new DirectoryInfo(sourceFile);
    
                    var files = directory.GetFiles()
                        .Where(x => x.Name.EndsWith(".pdf"))
                        .OrderBy(x => x.Name)
                        .Take(3).ToList();
    
    
                    foreach (FileInfo file in files)
                    {
                       System.IO.File.Move(sourceFile + file.Name, sourceFile + file.Name.Replace(extention, ".txt"));
    
                    }
                }
    
                catch (Exception ex)
                {
                    throw new ApplicationException("An error was encountered " + ex.Message);
                }


    Reason101

    Sunday, March 29, 2020 3:04 AM
  • This is what I meant - you should not modify files in your foreach loop. You need to use traditional for loop and do it backwards to be 100% sure.

    Take a look at the marked answer in this thread and try using that type of the loop

    https://stackoverflow.com/questions/275994/whats-the-best-way-to-do-a-backwards-loop-in-c-c-c


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles


    Sunday, March 29, 2020 3:09 AM
    Moderator
  • ok, can i have the code apply restrictions like below.

    1. There is a folder which has all pdf files (say 1000 pdf files in a folder)

    2. There is an external process which accessess these pdf files, so if there is pdf mask filename that external system picks the file.

    3. So, I am writing this code in .c# where it should restrict sending only 25 files .

    4. Also, the external system is also pointing to same folder and my c# code needs to be wrritten so it restricts sending sorted 25 files in same folder.

    Hope I am making sense. I feel little tricky, feel almost there but still not


    Reason101

    Sunday, March 29, 2020 3:26 AM
  • Thanks for your response. 

    I tried this, but receiving errors. Cannot convert String to IBaseMesage (inmsg)

     try
    
                {
                    string sourceFile = @"C:\UnitTest\Trigger\";
                    var directory = new DirectoryInfo(sourceFile);
    
                    var files = directory.GetFiles()
                        .Where(x => x.Name.EndsWith(".pdf"))
                        .OrderBy(x => x.Name)
                        .Take(3).ToList();
    
    
                    int n = 1;
                    for (int x = 0; x < files.Count; ++x)
                    {
                        inmsg = ("{0,2}==> {1}", n++, files[x]);
                    }
    
    
                    //foreach (FileInfo file in files)
                    //{
                    //    //    string extention = System.IO.Path.GetExtension(file.Name);
                    //    //    System.IO.File.Move(sourceFile + file.Name, sourceFile + file.Name.Replace(extention, ".txt"));
    
                    //}
                }
    
                catch (Exception ex)
                {
                    throw new ApplicationException("An error was encountered " + ex.Message);
                }
    
              return inmsg;


    Reason101

    Sunday, March 29, 2020 3:54 AM
  • This is not what I suggested at all. I suggested to use for loop going backwards and keep your original move as it was.

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Sunday, March 29, 2020 1:50 PM
    Moderator
  • I just tried this and it worked fine for me (3 files changed their extension):

     string sourcePath = @"path here";
    
             var directory = new DirectoryInfo(sourcePath);
    
             var files = directory.GetFiles()
                 .Where(x => x.Name.EndsWith(".txt"))
                 .OrderBy(x => x.Name)
                 .Take(3).ToList();
    
    
             for (int i = files.Count; i-- > 0;)
             {
                string fileName = files[i].FullName;
                Console.WriteLine(fileName);
                File.Move(fileName, Path.ChangeExtension(fileName, ".jpg"));
             }
             Console.ReadLine();


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Sunday, March 29, 2020 2:01 PM
    Moderator
  • Hi Naomi, thanks for your response. I tried with above code using for loop, its behaving same as for-each loop. While debugging in second or third file its looking for again previous file and throwing error , file not found. I mean its changing say 3rd file too .jpg and then looping again instead of going to 4th file, it is again for some reason looking for 3rd file and throwing error as file not found

    Reason101

    Monday, March 30, 2020 5:44 AM
  • Hi Reason101,

    Back to the starting point, I tried the code you provided multiple times and it correctly selected the required number of files without encountering any errors.

                string sourceFile = @" D:\test\xml\";
                var directory = new DirectoryInfo(sourceFile);
    
                var files = directory.GetFiles()
                    .Where(x => x.Name.EndsWith(".xml"))
                     .OrderBy(x => x.Name)
                     .Take(3).ToList();
                foreach (FileInfo file in files)
                {
                    string extention = System.IO.Path.GetExtension(file.Name);
                    File.Move(sourceFile + file.Name, sourceFile + file.Name.Replace(extention, ".txt"));                          
                }

    Foreach does not cause an error because foreach uses only fileinfo information to operate on the files in the folder, and the list itself has not changed.

    I can't understand why the "File not found" error occurs.

    Does the error really appear in this code? Did you use a code like "File.ReadAllLines (file.FullName)" elsewhere that caused a "file not found" error?

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 30, 2020 6:58 AM
  • Try it first exactly as I wrote (I tried in a console application).

    I didn't get any errors, all worked well. Try removing try/catch for now - perhaps the error is something else.

    Also, are you using Network drive or your own local drive? Try first from the directory which you created locally.


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Monday, March 30, 2020 1:08 PM
    Moderator
  • Hi Naomi/Timon, as per the code you provided  as we are taking 3 files at a time in the list and doing a for loop. How to send only those files out rather than doing any Move method and changing extension ?

    In for loop, I tried File.Create(abc[i]);

    Can you please advise, I just need the outputting of 3 files which are in the loop ?

    for (int i = files.Count; i-- > 0;)
             {
                string fileName = files[i].FullName;
                Console.WriteLine(fileName);
                File.Move(fileName, Path.ChangeExtension(fileName, ".jpg"));
             }


    Reason101

    Tuesday, March 31, 2020 1:04 AM
  • Did you try the code I provided? Did it work for you without errors?

    What exactly do you need to get done?


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Tuesday, March 31, 2020 1:17 AM
    Moderator
  • Almost there !!

    Yes its working fine, but what I need is what ever files selected in the (var Files) and then for those files we are doing a loop one after another I want those files to be outputted rather than doing any extension name change.

    What I mean to say is :

    if the file name in the folder is a1.txt,  within the for loop  I need to outout that selected 3 files without changing any extension.



    Reason101

    Tuesday, March 31, 2020 1:27 AM
  • That's what Console.WriteLine was doing in my loop. Just comment out the second line.

    If you need to output them into some text file (the file names), it is also quite easy.

    Don't forget Console.ReadLine() after the loop, otherwise you will not see the result.


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles


    Tuesday, March 31, 2020 2:01 AM
    Moderator
  • I dont want to see on the console, I just want the output ready to be sent out say if this code needs to move to production then I dont use Console.Readline() right ?


    Reason101

    Tuesday, March 31, 2020 2:07 AM
  • Ok, what kind of output would you want? You can instantiate a string builder variable before the loop and add files names into this variable and then it's ready for any kind of output you need.

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Tuesday, March 31, 2020 3:03 AM
    Moderator
  • Hi Naomi, can you please help me get the latest creation Time files from a folder. I am using below code.

    I want Order By Creation time

                    var files = Directory.EnumerateFiles(sPath, "*.pdf")                       
                              .OrderBy(f => f)
                              .Take(NumberOfFiles);
                    string[] xyz = files.ToArray();

    Please advise


    Reason101

    Monday, April 20, 2020 11:55 PM
  • Did you try search for your question?

    https://stackoverflow.com/questions/4765789/getting-files-by-creation-date-in-net


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    Tuesday, April 21, 2020 1:32 PM
    Moderator