VMware {code} Community
icnocop2
Contributor
Contributor

Get specific folder when there are multiple folders with the same name

Hi.

I'm trying to resolve a similar issue as described here:

Folder by Path - LucD notes

However, I'm trying to use the vSphere API to resolve the issue.

Trying to run the following code will display "Not found" when it's trying to find "UniqueFolderName" because FindEntityView will select the "wrong" "CommonFolderName" folder through the the first iteration of the loop.

In my environment, there's a "CommonFolderName" at the root Ievel and then another "CommonFolderName" that exists in a different folder at the second-level. l expected FindEntityView to select the "CommonFolderName" at the root level but it's actually selecting the one at the other level.

void Main()

{

    VimClient client = new VimClient();

    client.Login("https://vcenter/sdk/vimService", "username", "password");

    string hierarchyPath = "CommonFolderName/UniqueFolderName";

    Folder folder = GetFolder(client, null, hierarchyPath);

    if (folder == null)

    {

        Console.WriteLine("Not found");

    }

    else

    {

        Console.WriteLine("Found");

    }

}

private Folder GetFolder(VimClient client, ManagedObjectReference parent, string hierarchyPath)

{

    Folder folder = null;

    string[] parts = new string[] { null };

    if (hierarchyPath != null)

    {

        parts = hierarchyPath.Split(new[] { '/', '\\' });

    }

    foreach (string part in parts)

    {

        NameValueCollection folderFilter = null;

        if (part != null)

        {

           folderFilter = new NameValueCollection { { "name", part } };

        }

        Folder folderPart = (Folder)client.FindEntityView(typeof(Folder), parent, folderFilter, null);

        if (folderPart == null)

        {

            // failed to find folder

            return null;

        }

        folder = folderPart;

        parent = folderPart.MoRef;

    }

    return folder;

}

Any ideas?

Thank you.

0 Kudos
0 Replies