Wednesday, October 5, 2011

SQL table to a text file and an XML file

Writing records from SQL table to a text file and an XML file using C#.net

string conStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
string destinationFile= "C:\\CreateMe.txt";

FileStream stream = new FileStream(physicalPath, FileMode.Open, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter(stream);
SqlConnection con = new SqlConnection();
con.ConnectionString = conStr;
SqlCommand com = new SqlCommand("Select Name,ID FROM [User]", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
writer.Write(reader["Name"].ToString());
writer.Write(",");
writer.Write(reader["ID"].ToString());
writer.WriteLine();
}
reader.Close(); writer.Close(); stream.Close();

1 comment:

  1. Ever heard of using statement???or the try catch block???

    ReplyDelete