从C#中的文件夹和子文件夹中获取文件名

Get file names from folder and sub-folders in C#

我正在尝试从主文件夹和子文件夹中获取所有文件的名称和位置并将它们插入数据库,下面是我当前的实现并且工作正常但不包括子文件夹中的那些文件,请帮助修复下面的代码。谢谢

        static void Main(string[] args)
        {
            string VarDirectoryPath = "\\share\folder\";
            SqlConnection SQLConnection = new SqlConnection();
            SQLConnection.ConnectionString = SQLConnection.ConnectionString = "connectionString";
            string[] files = Directory.GetFiles(VarDirectoryPath);
            SqlCommand SqlCmd = new SqlCommand();
            SqlCmd.Connection = SQLConnection;
            SQLConnection.Open();
            foreach (string filename in files)
            {

                FileInfo file = new FileInfo(filename);

                SqlCmd.CommandText = "Insert into dbo.FileInformation(";
                SqlCmd.CommandText += "[FolderPath],[FileName],[LastWriteTime],[CreateTime],[FileSizeinKB])";
                SqlCmd.CommandText += " Values('"
                                  + VarDirectoryPath + "','"
                                  + file.Name + "','"
                                  + file.LastWriteTime + "','"
                                 + file.CreationTime
                                 + "','" + file.Length / 1024
                                 + "')";
                SqlCmd.ExecuteNonQuery();
            }
            SQLConnection.Close();
        }
    }
}

您可以使用

string[] files = Directory.GetFiles(VarDirectoryPath,"*.*",SearchOption.AllDirectories)

有关详细信息,您可以阅读 msdn-Directory.GetFiles