Search code examples
sql-servercsvdappercsvhelper

Using Dapper I want to write a CSV text file reading an Instrument table from sql database with Console.WriteLine


Using https://joshclose.github.io/CsvHelper/) I'm trying to write a csv text file with the Console.WriteLine output from an Instrument table connected to sqlserver using Dapper.

my initial code to open DB and process records is

using (var dbconn = new SqlConnection(sb.ConnectionString))
        {
            var fred = dbconn.Query<Instrument>("SELECT * FROM Instruments");
            foreach (var s in fred)

            {
                Console.WriteLine($"{s.SurgicalDeviceId}, {s.CreatedAt}");

Now i've been reading up on this and a few people have said by using Console.WriteLine I can make a simple and clean code to create the csv file but I seem to be having no luck trying it myself.

Could anyone help write the code or point me in the direction where this has been done with Console.WriteLine?


Solution

  • If you want to use CsvHelper to write the records to file.csv, this should work for you.

    using (var dbconn = new SqlConnection(sb.ConnectionString))
            {
                var records = dbconn.Query<Instrument>("SELECT * FROM Instruments").ToList();
    
                using (var streamWriter = new StreamWriter("path\\to\\file.csv"))
                using (var csvWriter = new CsvWriter(streamWriter))
                {
                    csvWriter.WriteRecords(records);
                }