user11328958
user11328958

Reputation:

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

I am trying to get name and location of all files from main folder and sub-folders and insert them in database, below is my current implementation and working fine but does not include those files that are in sub-folders, please help fix code below. thanks

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

Upvotes: 0

Views: 689

Answers (1)

Svyatoslav Ryumkin
Svyatoslav Ryumkin

Reputation: 374

You can use

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

for more details you can read msdn-Directory.GetFiles

Upvotes: 1

Related Questions