.Net Almanac

Monday, October 31, 2005

Reading from a Text File

Just like "writing", reading is a simple task either:

TextReader reader = new StreamReader("filename.txt");

string line = reader.ReadLine()

reader.Close();

Wednesday, October 26, 2005

Writing to a Text File

Although it is one of the mostly used and simplest tasks, people forget it all the time and need to remember before using it. It goes like this:

TextWriter writer = new StreamWriter("filename.txt");

writer.WriteLine("Anything you want...");

writer.Close();

Tuesday, October 25, 2005

Using Transaction

When we wat to use a transaction structure when connecting and updating a database, what we need to do is very simple:

SqlConnection con = new SqlConnection("...");
con.Open();
SqlTransaction trans = con.BeginTransaction();
try
{
string sql = "INSERT INTO ...";
SqlCommand command = new SqlCommand(sql, con, trans);
command.ExecuteNonQuery();
command.CommandText = "UPDATE ...";
command.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
finally
{
con.Close();
}