C# .NET - Convert Web to Console - Asked By Jem Savery on 13-Dec-11 06:15 AM

Hi Friends,

I need following web application code to be used in Console application in C#.


DataTable toExcel = test.Copy();
HttpContext context = HttpContext.Current;


foreach (DataColumn column in toExcel.Columns)
{
     context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);


foreach (DataRow row in toExcel.Rows)
{
     for (int i = 0; i < toExcel.Columns.Count; i++)
     {
          context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
     }
     context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
context.Response.End();


Please help.


Thanks in advance.
dipa ahuja replied to Jem Savery on 13-Dec-11 06:39 AM
using System.Text;
using System.Data;
 
namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      DataTable toExcel = test.Copy();
      
 
      foreach (DataColumn column in toExcel.Columns)
      {
        Console.Write(column.ColumnName + ",");
      }
      Console.Write(Environment.NewLine);
 
 
      foreach (DataRow row in toExcel.Rows)
      {
        for (int i = 0; i < toExcel.Columns.Count; i++)
        {
          Console.Write(row[i].ToString().Replace(","string.Empty) + ",");
        }
        Console.Write(Environment.NewLine);
      }       
    }
  }
}
Jem Savery replied to dipa ahuja on 13-Dec-11 08:10 AM
How will I export the csv file then? using Console?
dipa ahuja replied to Jem Savery on 13-Dec-11 09:47 AM
class Program
{
  static void Main(string[] args)
  {
    DataTable toExcel = test.Copy();
      
 
    foreach (DataColumn column in toExcel.Columns)
    {
      Console.Write(column.ColumnName + ",");
    }
    Console.Write(Environment.NewLine);
 
      
      // Write the string to a file.
    System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\test.txt");
      
 
      string content = "";
 
    foreach (DataRow row in toExcel.Rows)
    {
      for (int i = 0; i < toExcel.Columns.Count; i++)
      {
        Console.Write(row[i].ToString().Replace(","string.Empty) + ",");
        content += row[i].ToString().Replace(","string.Empty) + ",";
        file.WriteLine(content);
 
      }
 
      Console.Write(Environment.NewLine);
    }
      file.Close();     
  }
}