web analytics

Converting Between ArrayList and Array in C#

Options

codeling 1599 - 6654
@2021-03-21 08:59:00

From time to time, you may need to do the conversion between ArrayList and Array when you are coding in C#. The following C# code demonstrates how to do these.

Converting Array to ArrayList 
ArrayList fileArrayList = = new ArrayList();
string[] files = Directory.GetDirectories(path)
fileArrayList.AddRange(files);
Converting ArrayList to Array
ArrayList fileArrayList = new ArrayList();
//Populate fileArrayList
...
string[] files = (string[])fileArrayList.ToArray(
typeof(string));

 

@2021-03-21 10:05:04
Example

public static string[] GetFiles(string path, bool recursive)
{
  ArrayList fileArrayList = new ArrayList();

  DirectoryManager.ValidateDirectoryPath( path);

  if (DirectoryManager.Exists(path))
  {
   fileArrayList.AddRange(Directory.

GetFiles(path));

   if (recursive)
   {
    foreach (string dir in Directory.GetDirectories(path))
    {
     fileArrayList.AddRange(

DirectoryManager.

GetFiles(dir, recursive));
    }
   }
  }

  return (string[])fileArrayList.ToArray(

typeof(string));
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com