Hi All,
I can connect C# to SQL and read SQL table but i am having problem in writing the outcome to text file. I really appreciate if you could assist me.
this is the code.
//======================================
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace Chapter07
{
class OrdinalIndexer
{
static void Main(string[] args)
{
// connection string
// connection string
string connString =
@" server = (local);
database = FoodMart 2005;
integrated security = sspi";
// query
string sql = @"
select [lname] ,[fname] ,[account_num]
from
customer
";
// create connection
SqlConnection conn = new SqlConnection(connString);
try
{
// Open connection
conn.Open();
// create command
SqlCommand cmd = new SqlCommand(sql, conn);
// create data reader
SqlDataReader rdr = cmd.ExecuteReader();
// print headings
Console.WriteLine("\t{0} {1} {2}",
"lname".PadRight(10),
"fname".PadRight(10),
"account_num".PadRight(10)
);
Console.WriteLine("\t{0} {1} {2}",
"============".PadRight(10),
"============".PadRight(10),
"============".PadRight(10)
);
// open writing file
StreamWriter w1 = new StreamWriter("c:\\2.txt");
// loop through result set
while (rdr.Read())
{
Console.WriteLine(" {0} | {1} | {2}",
rdr[0].ToString().PadLeft(10),
rdr[1].ToString().PadLeft(10),
rdr[2].ToString().PadLeft(10)
);
// loop for writing the result
// here is the problem but i do not know how to solve it
string line1;
while ((line1 = rdr.ReadLine()) != null)
{
w1.WriteLine(line1);
Console.WriteLine(line1);
}
}
// close reader
rdr.Close();
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e);
}
finally
{
// close connection
Console.Read();
conn.Close();
}
}
}
}
Thank you very much in advance.
Regards,
Nony