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;
}

我想转换FI。Name到字符串中,然后将其添加到数组中。我该怎么做呢?


当前回答

这是我在需要时添加字符串的方法:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}

其他回答

这是我在需要时添加字符串的方法:

string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
    myList[i] = string.Format("List string : {0}", i);
}

在这种情况下,我不会使用数组。相反,我将使用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;
}
string[] MyArray = new string[] { "A", "B" };
MyArray = new List<string>(MyArray) { "C" }.ToArray();
//MyArray = ["A", "B", "C"]

或者,您可以调整数组的大小。

Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";

使用System.Linq添加对Linq的引用;并使用提供的扩展方法追加:公共静态IEnumerable<TSource>追加<TSource>(此IEnumerable<TSource>源,TSource元素) 然后你需要使用. toarray()方法将它转换回字符串[]。

这是可能的,因为类型string[]实现了IEnumerable,它也实现了以下接口:IEnumerable<char>, IEnumerable, IComparable, IComparable< string >, IConvertible, IEquatable< string >, ICloneable

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

请记住,ToArray分配新的数组,因此,如果你添加更多的元素,你不知道你将有多少,最好使用List from System.Collections.Generic。