Count the number of files in one directory

Hello,

I’m trying to make a kind of music player. I intend to create a folder, “music”, in which people will put their songs in.
But I don’t want unity to just open them. I want unity to count the number of songs in the folder and, depending on the number, to take different actions.

Is there any easy way to do this?

1 Answer

1

You can use the System.IO.DirectoryInfo class.

Adapted from the example they gave:

public static long DirCount(DirectoryInfo d)
{
    long i = 0;
    // Add file sizes.
    FileInfo[] fis = d.GetFiles();
    foreach (FileInfo fi in fis)
    {
        if (fi.Extension.Contains("mp3"))
            i++;
    }

    return i;
}

Thank you for the help :) I'll try it out as soon as I can

Thanks for this, I found it useful. Just I would look for the extension this way for better precision: if (fi.Extension.Equals (".mp3", StringComparison.OrdinalIgnoreCase)) i++;