将数组数据添加到列表:无法将System.DirectoryInfo []转换为字符串

时间:2017-03-19 08:45:09

标签: c#

所以基本上是我的noob尝试索引和存储数据。我创建了两个列表,使用DirectoryInfo类存储来自不同阵列的目录和文件。

我在SubDirectoriesList.Add(subdirectories);DirectoryInfo[] directoryFiles = di.GetFiles(SubDirectoriesList);FilesList.Add(directoryFiles);收到编译错误。

他们中的大多数人都说:

  

使用未分配的局部变量。无法转换   System.DirectoryInfo []到字符串。

我尝试了一些不同的东西,感觉非常接近。我已经回顾了几个c#List教程,但是无法将超级简单的例子翻译成我的函数。

        List<string> FilesList;
        List<string> SubDirectoriesList;

        DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);

        //GETS SUBDIRECTORIES FROM SELECTED PATH
        DirectoryInfo[] subdirectories = di.GetDirectories();
        for (int i = 0; subdirectories.Length >= 0; i++)
        {
            if (i > subdirectories.Length - 1)
            {
                break;
            }

            //ADD SUBDIRECTORIES TO LIST
            SubDirectoriesList.Add(subdirectories);
        }

        //GETS FILES FROM SUBDIRECTORIES IN LIST
        DirectoryInfo[] directoryFiles = di.GetFiles(SubDirectoriesList);
        for (int i = 0; directoryFiles.Length >= 0; i++)
        {
            if (i > directoryFiles.Length - 1)
            {
                break;
            }

            //ADD FILES TO FILES LIST
            FilesList.Add(directoryFiles);
        }
    }

2 个答案:

答案 0 :(得分:0)

我认为你是在尝试这个:

List<string> FilesList = new List<string>();
List<string> SubDirectoriesList = new List<string>();

DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));

//GETS SUBDIRECTORIES FROM SELECTED PATH
DirectoryInfo[] subdirectories = di.GetDirectories();
for (int i = 0; subdirectories.Length >= 0; i++)
{
    if (i > subdirectories.Length - 1)
    {
        break;
    }

    //ADD SUBDIRECTORIES TO LIST
    SubDirectoriesList.Add(subdirectories[i].FullName);
}

//GETS FILES FROM SUBDIRECTORIES IN LIST

//Loop all sub directory files
foreach (var fileItem in SubDirectoriesList)
{
    string[] directoryFiles =  Directory.GetFiles(fileItem);
    for (int i = 0; directoryFiles.Length >= 0; i++)
    {
        if (i > directoryFiles.Length - 1)
        {
            break;
        }

        //ADD FILES TO FILES LIST
        FilesList.Add(directoryFiles[i]);
    }

}

答案 1 :(得分:0)

在尝试添加之前,您似乎没有初始化列表 SubDirectoriesList