How to add a string to a string[] array? There's no .Add function
Solution 1:
You can't add items to an array, since it has fixed length. What you're looking for is a List<string>
, which can later be turned to an array using list.ToArray()
, e.g.
List<string> list = new List<string>();
list.Add("Hi");
String[] str = list.ToArray();
Solution 2:
Alternatively, you can resize the array.
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
Solution 3:
Use List<T> from System.Collections.Generic
List<string> myCollection = new List<string>();
…
myCollection.Add(aString);
Or, shorthand (using collection initialiser):
List<string> myCollection = new List<string> {aString, bString}
If you really want an array at the end, use
myCollection.ToArray();
You might be better off abstracting to an interface, such as IEnumerable, then just returning the collection.
Edit: If you must use an array, you can preallocate it to the right size (i.e. the number of FileInfo you have). Then, in the foreach loop, maintain a counter for the array index you need to update next.
private string[] ColeccionDeCortes(string Path)
{
DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion = new string[listaDeArchivos.Length];
int i = 0;
foreach (FileInfo FI in listaDeArchivos)
{
Coleccion[i++] = FI.Name;
//Add the FI.Name to the Coleccion[] array,
}
return Coleccion;
}
Solution 4:
Eazy
// Create list
var myList = new List<string>();
// Add items to the list
myList.Add("item1");
myList.Add("item2");
// Convert to array
var myArray = myList.ToArray();