Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Minor Issue when Iterating through file

I have a program that iterates through all files from directories and subdirectories, it’s working smoothly but there is just a minor issue that my brain can’t solve.
The one finding the simplest way to solve it is a genius 🙂

Here is the code :

    int hello(string locat)
    {
        string[] files = Directory.GetFiles(locat);
        string[] dirs = Directory.GetDirectories(locat);
        int cpt = 0;
        
        foreach (var file in files)
        {
            try
            {
                textBox1.AppendText(file+"\r\n");

                cpt++;
                textBox2.AppendText(cpt.ToString()+"\r\n");
            }
            catch { }
        }

        
        foreach (string directory in dirs)
        {
            try
            {
                cpt += hello(directory);
            }
            catch { }
        }

        return cpt;

    }

So the problem is that the output of cpt inside textBox2 have a logic behavior but a behavior that is not adequate for my needs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is how it looks like :

1
2
3
1
2
1
2
...

And I want it to be 1,2,3,4,5,6,7,8,9,…

I tried with EnumerateFiles instead of GetFiles, it was working smoothly too but i got some permissions issue and I’m working on .NET framework for this project

>Solution :

A variation that avoids ref

int hello(string locat, int counter = 0)
{
    string[] files = Directory.GetFiles(locat);
    string[] dirs = Directory.GetDirectories(locat);
        

    foreach (var file in files)
    {
        try
        {
            textBox2.AppendText(file + "\r\n");

            counter++;
            textBox2.AppendText(counter.ToString() + "\r\n");
        }
        catch { }
    }


    foreach (string directory in dirs)
    {
        try
        {
            counter = hello(directory, counter);
        }
        catch { }
    }

    return counter;

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading