C# - How to Export all the tables from a database to flat files by using C Sharp

Scenario : Download Script

You are working as C# developer, You need to create an C# program that should create flat files for all the tables from a database dynamically. There should be one file for each table and it should be created with date-time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SqlClient;
using System.Data;


namespace TechBrothersIT.com_CSharp_Tutorial {
 class Program {
  static void Main(string[] args) {

   string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
   string LogFolder = @ "C:\Log\";
   try {

    //Declare Variables and provide values
    string DestinationFolder = @ "C:\Destination\"; //Provide the destination folder
    string FileDelimiter = ","; //Provide the file delimiter such as comma or pipe
    string FileExtension = ".txt"; //Provide the extension such as .txt or .csv


    //Create Connection to SQL Server
    SqlConnection SQLConnection = new SqlConnection();
    SQLConnection.ConnectionString = "Data Source = (local); Initial Catalog =TechBrothersIT; " + "Integrated Security=true;";

    //Read list of Tables with Schema from Database
    string query = "SELECT Schema_name(schema_id) AS SchemaName,name AS TableName FROM   sys.tables WHERE  is_ms_shipped = 0";


    SqlCommand cmd = new SqlCommand(query, SQLConnection);
    SQLConnection.Open();
    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());

    //Loop through datatable(dt) that has schema and table names
    foreach(DataRow dt_row in dt.Rows) {
     string SchemaName = "";
     string TableName = "";
     object[] array = dt_row.ItemArray;
     SchemaName = array[0].ToString();
     TableName = array[1].ToString();

     string FileFullPath = DestinationFolder + "\\" + SchemaName + "_" + TableName + "_" + datetime + FileExtension;

     //Get the data for a table into data table 
     string data_query = "Select * From [" + SchemaName + "].[" + TableName + "]";
     SqlCommand data_cmd = new SqlCommand(data_query, SQLConnection);
     DataTable d_table = new DataTable();
     d_table.Load(data_cmd.ExecuteReader());

     StreamWriter sw = null;
     sw = new StreamWriter(FileFullPath, false);

     // Write the Header Row to File
     int ColumnCount = d_table.Columns.Count;
     for (int ic = 0; ic < ColumnCount; ic++) {
      sw.Write(d_table.Columns[ic]);
      if (ic < ColumnCount - 1) {
       sw.Write(FileDelimiter);
      }
     }
     sw.Write(sw.NewLine);

     // Write All Rows to the File
     foreach(DataRow dr in d_table.Rows) {
      for (int ir = 0; ir < ColumnCount; ir++) {
       if (!Convert.IsDBNull(dr[ir])) {
        sw.Write(dr[ir].ToString());
       }
       if (ir < ColumnCount - 1) {
        sw.Write(FileDelimiter);
       }
      }
      sw.Write(sw.NewLine);

     }

     sw.Close();

    }
    SQLConnection.Close();

   } catch (Exception exception) {
    // Create Log File for Errors
    using(StreamWriter sw = File.CreateText(LogFolder + "\\" + "ErrorLog_" + datetime + ".log")) {
     sw.WriteLine(exception.ToString());

    }

   }

  }
 }
}


I executed above code and it export all the tables from SQL Server Database to text files.
How to Export all the tables form SQL Server Database to Flat files ( CSV Files) by using C#
 

No comments:

Post a Comment