Daniel Lip
Daniel Lip

Reputation: 11325

How can i get a string and return each time a string from array?

I have this function :

private string offline(string targetDirectory)
        {
            string directory = ""; 
            try
            {
                string[] dirs = Directory.GetDirectories(targetDirectory,"*.*",SearchOption.TopDirectoryOnly);
                for (int i = 0; i < dirs.Length; i++)
                {
                    directory = dirs[i];
                }
            }
            catch
            {

            }
            return directory;

        }

For example if targetDirectory is c:\ then i get in the array 14 directories. Now i want that each time i call the function offline it will return me once the first string c:\$Recycle.Bin Then it will return c:\test and each time i call the function it will return the next string from the array. Since im using a recrusive function and calling this offline function from a recrusive i want it to return each time the next string from the array.

Now as it is now it will return the last directory in the array only and thats it.

How can i do it ?

Upvotes: 1

Views: 91

Answers (1)

zmbq
zmbq

Reputation: 39023

Easiest way - use yield:

IEnumerable<string> offline(string dir)
{
    ...
    ... instead of directory = dirs[i] do
    yield return dirs[i];
}

Upvotes: 4

Related Questions