vcltstringlistc++builder-xe5tstringdynarray

How to convert a TStringDynArray to a TStringList


I'm using TDirectory::GetFiles() to get a list of files (obviously). The result is stored in a TStringDynArray and I want to transfer it to a TStringList for the sole purpose to use the IndexOf() member to see if a string is present in the list or not.

Any solution that will let me know if a certain string is present in the list of files returned from TDirectory::GetFiles() will do fine. Although, it would be interesting to know how to convert the TStringDynArray.

TStringDynArray DynFiles = TDirectory::GetFiles("Foo path");
System::Classes::TStringList *Files = new System::Classes::TStringList;

Files->Assing(DynFiles) // I know this is wrong, but it illustrates what I want to do.
if(Files->IndexOf("Bar") { // <---- This is my goal, to find "Bar" in the list of files.

}

Solution

  • TStringList and TStringDynArray do not know anything about each other, so you will have to copy the strings manually:

    TStringDynArray DynFiles = TDirectory::GetFiles("Foo path");
    System::Classes::TStringList *Files = new System::Classes::TStringList;
    
    for (int I = DynFiles.Low; I <= DynFiles.High; ++I)
        Files->Add(DynFiles[I]);
    
    if (Files->IndexOf("Bar")
    {
        //...
    }
    
    delete Files;
    

    Since you have to manually loop through the array anyway, you can get rid of the TStringList:

    TStringDynArray DynFiles = TDirectory::GetFiles("Foo path");
    
    for (int I = DynFiles.Low; I <= DynFiles.High; ++I)
    {
        if (DynFiles[I] == "Bar")
        {
            //...
            break;
        }
    }
    

    But, if you are only interested in checking for the existence of a specific file, look at TFile::Exists() instead, or even Sysutils::FileExists().

    if (TFile::Exists("Foo path\\Bar"))
    {
        //...
    }
    

    if (FileExists("Foo path\\Bar"))
    {
        //...
    }
    

    * personally, I hate that the IOUtils unit uses dynamic arrays for lists. They are slow, inefficient, and do not integrate well with the rest of the RTL. But that is just my opinion.