C# csv to SQL Server database table by file date modified [closed]

Looking for C# code that will locate the .csv file with the most recent date modified in a folder and insert that data into a SQL Server table.

1 Answer

When you say insert data into sql do you mean just the name of the .csv file into sql or the data within the csv file? if that’s the case

look at code below:

Make sure to create a table in your mysql named “users” and within the table create a key called “name” within the users table

        private void button1_Click(object sender, EventArgs e)   //this is button1 click
       string pattern = "*.csv";
        var directory = new DirectoryInfo("C:\mine");  
        var myFile = (from f in directory.GetFiles(pattern)
                      orderby f.LastWriteTime descending
                      select f).First();

            string myString = myFile.ToString();
            textBox1.Text = myString;   // create a textbox1

            String Myconnection = "datasource=yoursqlserver.net;port=3306;username=sqlusername;password=xxxxxx;database=databasename";
            MySqlConnection databaseConnection = new MySqlConnection(Myconnection);

            String sqlSelectQuery = "INSERT INTO users(Name) VALUES ('"+this.textBox1.Text +"')";

            if (textBox1.Text != "")

                MySqlCommand commandDatabase = new MySqlCommand(sqlSelectQuery, databaseConnection);
                MySqlDataReader dr = commandDatabase.ExecuteReader();

MessageBox.Show("Your Most recent data name send to sql")

            else { MessageBox.Show("DID not locate anything in folder"); }


if you want the data within the csv file and not the csv file name then you can use StreamReader class and put it in the code above.

StreamReader sr = new StreamReader(filepath);
    string line = sr.ReadLine();
    string[] value = line.Split(',');
    DataTable dt = new DataTable();
    DataRow row;

    foreach (string dc in value)
        dt.Columns.Add(new DataColumn(dc));

Archive from: https://stackoverflow.com/questions/59061420/c-sharp-csv-to-mssql-db-table-by-file-date-modified

Leave a Reply

Your email address will not be published. Required fields are marked *