1

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 ?

1
  • 2
    I'm not sure I follow, but it sounds like you want to implement an iterator, i.e. a method that returns IEnumerable<string>. Take a look at msdn.microsoft.com/en-us/library/dd383573.aspx for an example that comes close to what you're talking about. Commented Oct 24, 2012 at 22:34

1 Answer 1

4

Easiest way - use yield:

IEnumerable<string> offline(string dir)
{
    ...
    ... instead of directory = dirs[i] do
    yield return dirs[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I agree this is how to do this, though there is something to be said for him just returning the original output of Directory.GetDirectories and using that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.