using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.IO;
namespace ExportDataTableApplication
{
class ExportDataTable
{
DateTime datetime = DateTime.Now;
static void Main(string[] args)
{
Console.WriteLine("Running App");
ExportDataTable program = new ExportDataTable();
DataSet ds = new DataSet();
DateTime datetime = DateTime.Now;
try
{
using (SqlConnection conn = new SqlConnection("Test connection string"))
{
SqlCommand sqlComm = new SqlCommand("Test", conn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(sqlComm);
da.Fill(ds);
}
StreamWriter sw = null;
StringBuilder sb = new StringBuilder();
foreach (DataTable dt in ds.Tables)
{
sw = new StreamWriter(string.Format(@"C:\Users\Desktop\ConsoleApplication2\ConsoleApplication2\CSV File\Export{0}" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".csv", dt.TableName));
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if ((!Convert.IsDBNull(dr[i])) && (i == 7))
{
sw.Write(dr[i].ToString().Replace("\r", " "));
}
else
{
sw.Write(dr[i].ToString().Replace(",", " "));
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
Console.WriteLine("App ran successfully");
}
catch(Exception exp)
{
program.log(exp.Message);
}
}
public void log(String message)
{
String oFileName = @"C:\Users\Desktop\ConsoleApplication2\ConsoleApplication2\Log\Log_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".txt";
if (!File.Exists(oFileName))
{
System.IO.FileStream f = File.Create(oFileName);
f.Close();
}
try
{
System.IO.StreamWriter writter = File.AppendText(oFileName);
writter.WriteLine(datetime.ToString("dd-MM-yyyy_hh-mm-ss") + " > " + message );
writter.Flush();
writter.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
}
}
If you find any issue then let me know.