286
private string[] ColeccionDeCortes(string Path)
{
    DirectoryInfo X = new DirectoryInfo(Path);
    FileInfo[] listaDeArchivos = X.GetFiles();
    string[] Coleccion;

    foreach (FileInfo FI in listaDeArchivos)
    {
        //Add the FI.Name to the Coleccion[] array, 
    }

    return Coleccion;
}

I'd like to convert the FI.Name to a string and then add it to my array. How can I do this?

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

15 Answers15

516

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();
Saulius Valatka
  • 7,017
  • 5
  • 26
  • 27
153

Alternatively, you can resize the array.

Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
  • 7
    `Array.Resize` *is* the proper way to resize an array. If you add a comment before the code snippet saying it's rarely the best way to handle situations where the array represents a resizable collection you've got a +1. :) – Sam Harwell Sep 17 '09 at 17:56
  • 23
    Actually, this is the (only) answer that exactly solves the OP question. – dialex Nov 07 '15 at 19:48
  • 1
    in C# 8 you can do `array[^1]` instead of `array[array.Length -1]` – nedstark179 Feb 23 '22 at 20:35
73

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;
}
Guybrush Threepwood
  • 1,096
  • 2
  • 10
  • 18
Adam Wright
  • 48,938
  • 12
  • 131
  • 152
32

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();
scre_www
  • 2,536
  • 4
  • 20
  • 30
NoloMokgosi
  • 1,678
  • 16
  • 10
10

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)
Druid
  • 6,423
  • 4
  • 41
  • 56
Stefan Nicolov
  • 109
  • 1
  • 2
6

This is how I add to a string when needed:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}
ItsJ0el
  • 55
  • 1
  • 5
kittugadu
  • 61
  • 1
  • 2
4

Why don't you use a for loop instead of using foreach. In this scenario, there is no way you can get the index of the current iteration of the foreach loop.

The name of the file can be added to the string[] in this way,

private string[] ColeccionDeCortes(string Path)
{
  DirectoryInfo X = new DirectoryInfo(Path);
  FileInfo[] listaDeArchivos = X.GetFiles();
  string[] Coleccion=new string[listaDeArchivos.Length];

  for (int i = 0; i < listaDeArchivos.Length; i++)
  {
     Coleccion[i] = listaDeArchivos[i].Name;
  }

  return Coleccion;
}
Sarath Rachuri
  • 2,086
  • 2
  • 18
  • 18
  • Only issue: you MUST know what your length of `listaDeArchivos` is. If you don't (i.e. if it could ever change and it would be complex to do a count ahead of time because your objects are nested models or model fields that may/may not be filled, for example) and you just want to do `string[] Coleccion;` then assign it like `int idx = 0; Coleccion[idx] = fileName; idx++;`, it will tell you `Use of unassigned local variable 'Coleccion'`. Just FYI for anyone wanting to adapt this to be more dynamic, that there's a pitfall. – vapcguy Oct 03 '18 at 18:12
2
string[] coleccion = Directory.GetFiles(inputPath)
    .Select(x => new FileInfo(x).Name)
    .ToArray();
xcud
  • 14,422
  • 3
  • 33
  • 29
1

This code works great for preparing the dynamic values Array for spinner in Android:

    List<String> yearStringList = new ArrayList<>();
    yearStringList.add("2017");
    yearStringList.add("2018");
    yearStringList.add("2019");


    String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);
Taras Vovkovych
  • 4,062
  • 2
  • 16
  • 21
1
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]
  • It might be a good idea to explain why an array is a bad choice here and OP should use List<> to begin with. – LueTm Apr 25 '18 at 12:32
1

Adding a reference to Linq using System.Linq; and use the provided extension method Append: public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element) Then you need to convert it back to string[] using the .ToArray() method.

It is possible, because the type string[] implements IEnumerable, it also implements the following interfaces: IEnumerable<char>, IEnumerable, IComparable, IComparable<String>, IConvertible, IEquatable<String>, ICloneable

using System.Linq;
public string[] descriptionSet new string[] {"yay"};
descriptionSet = descriptionSet.Append("hooray!").ToArray(); 

Remember that ToArray allocates new array, therefore if you're adding more elements and you don't know how much of them you're going to have it's better to use List from System.Collections.Generic.

proximab
  • 1,865
  • 1
  • 13
  • 18
0

I would not use an array in this case. Instead I would use a StringCollection.

using System.Collections.Specialized;

private StringCollection ColeccionDeCortes(string Path)   
{

    DirectoryInfo X = new DirectoryInfo(Path);

    FileInfo[] listaDeArchivos = X.GetFiles();
    StringCollection Coleccion = new StringCollection();

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion.Add( FI.Name );
    }
    return Coleccion;
}
DatRid
  • 1,169
  • 2
  • 21
  • 46
0

to clear the array and make the number of it's elements = 0 at the same time, use this..

System.Array.Resize(ref arrayName, 0);
DeyaEldeen
  • 10,847
  • 10
  • 42
  • 75
0

Create an extention:

public static class TextFunctions
{
    public static string [] Add (this string[] myArray, string StringToAdd)
    {
          var list = myArray.ToList();
          list.Add(StringToAdd);
          return list.ToArray();
    }
}

And use it as such:

foreach (FileInfo FI in listaDeArchivos)
{
    //Add the FI.Name to the Coleccion[] array, 
    Coleccion.Add(FI.Name);
}
Gregory Liénard
  • 1,071
  • 3
  • 7
-1

I would do it like this:

DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion = new String[] { };

foreach (FileInfo FI in listaDeArchivos)
{
    Coleccion = Coleccion.Concat(new string[] { FI.Name }).ToArray();
}

return Coleccion;