Count number of folders in a directory

Hi, I’m trying to figure out how to count the number of files in a directory and then create buttons for each of those directories.

So far I can create directories in a specified directory if it doesn’t already exist.

if (System.IO.Directory.Exists ("C:\\Diary\\" + newDiaryName.text + "\\"))
                {
                    //Folder Exists
                    Debug.Log ("Directory already exists");

                }
                else
                {
                    //Create Folder
                    System.IO.Directory.CreateDirectory ("C:\\Diary\\" + newDiaryName.text + "\\");

                }

What I want to do is is display buttons that represent the directories in the “Diary” folder. So I need to loop and add each directory to a list.

I’m having trouble finding info on searching for folders rather than actual files.

Any one able to enlighten me?

Thanks!

Have you looked at Directory.GetDirectories?
It takes a string path and returns the list of directory/sub directory names.

1 Like

I haven’t done it, but a quick search came up with this example:

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("c:\\");
int count = dir.GetFiles().Length;

This link also tells you how to iterate through subdirectories and stuff too, as that might be what you meant…?

2 Likes

Thank you, I had looked at those links but was still a little unsure. Never the less I’ve managed to sort it.

DirectoryInfo dir = new DirectoryInfo (homeDir);
        DirectoryInfo[] info = dir.GetDirectories ("*.*");
        int count = dir.GetDirectories().Length;
        for (int i = 0; i < count; i++)
        {
            Debug.Log ("Found Directory: " + info[i]);
        }

Thanks for your help guys!

2 Likes