Search This Blog

2010/01/17

Reading MSSQL data using datareader ,command object,connection object & writing the data to plane text file:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlClient;


namespace writing_data_to_text_file_in_csharp
{
class Program
{

static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=(Local);Initial Catalog = Sangram;Integrated Security=SSPI");
con.Open();

SqlCommand cmd = new SqlCommand("select * from course", con);
SqlDataReader dr = cmd.ExecuteReader();

string strPath ="I:\\trial\\Course.txt";
//writing data to text file
writeToFile(dr,strPath);

//releases datareader object
dr.Close();
dr.Dispose();

//releases connection object
con.Close();
con.Dispose();

//releases command object
cmd.Dispose();

}

private static void writeToFile(SqlDataReader dr1,string Path)
{

FileStream fstream= new FileStream(Path , FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter swriter= new StreamWriter(fstream);

while(dr1.Read())
{
string textrow;
textrow = dr1["cno"].ToString();
textrow = textrow+ " " + dr1["cname"];
textrow = textrow + " " + dr1["duration"].ToString();
textrow = textrow + " " + dr1["fees"].ToString();
swriter.WriteLine(textrow);
}
swriter.Close();
swriter.Dispose();

fstream.Close();
fstream.Dispose();

dr1.Close();
dr1.Dispose();
}
}

}

No comments:

Post a Comment