【问题标题】:Get file names from folder and sub-folders in C#从 C# 中的文件夹和子文件夹中获取文件名
【发布时间】:2021-03-22 19:52:04
【问题描述】:

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

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

【问题讨论】:

  • 文件系统是一棵树(或者在某些情况下是一个有向图)。您将需要学习如何使用递归或堆栈或队列来遍历树,然后将其应用于文件系统。
  • 请不要通过字符串连接创建SQL命令;使用参数化查询。您可能会对 SQL 注入漏洞敞开心扉。
  • 这真的是一个 asp.net 应用程序吗?你为什么要这样标记它?

标签: c# asp.net-mvc asp.net-core c#-4.0


【解决方案1】:

你可以使用

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

更多详情可以阅读msdn-Directory.GetFiles

【讨论】:

  • 谢谢 Svyatoslav Ryumkin,工作完美!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多