HarshSharma
HarshSharma

Reputation: 660

File Writing Exception Handling

I need some suggestion on the below code in which, i am writing some data into the file and at the same time and i updating records in the database.

foreach (DataRow dr in dtCSVdata.Rows)
{
    StringBuilder sbData = new StringBuilder();

    //Below line of code is used to write data in database
    SQLHelper.MoveOtherQuotesToWaitingArivalOfBags(quoteHeaderId, Config.WSUserName, refCode);

    foreach (object obj in dr.ItemArray)
    {
         if (sbData.Length == 0)
         {
             sbData.Append("\"");
             sbData.Append(RemoveSpecialCharacters(obj.ToString()));
             sbData.Append("\"");
         }
         else
         {
              sbData.Append(",");
              sbData.Append("\"");
              sbData.Append(RemoveSpecialCharacters(obj.ToString()));
              sbData.Append("\"");
         }
     }
     //Write to file
     writer.WriteLine(sbData.ToString());
}

Sometimes timeout exception occurs while updating the records in database and when exception occurs control is passed to the catch block and no data is being written into the file.

Suppose if there were 100 records and loop has just updated the 50 records then there would be no data written in the file for 50 records. So, it becomes very difficult to track what records has been updated.

Can you please help me in this as i want if something goes wrong then data in the file should be written before that.

Upvotes: 0

Views: 74

Answers (1)

Kryptonian
Kryptonian

Reputation: 870

Just move the line to insert data after writing to file,

foreach (DataRow dr in dtCSVdata.Rows)
{
 StringBuilder sbData = new StringBuilder();

//comment Below line of codewhich is used to write data in database
// SQLHelper.MoveOtherQuotesToWaitingArivalOfBags(quoteHeaderId, Config.WSUserName, refCode);

foreach (object obj in dr.ItemArray)
{
     if (sbData.Length == 0)
     {
         sbData.Append("\"");
         sbData.Append(RemoveSpecialCharacters(obj.ToString()));
         sbData.Append("\"");
     }
     else
     {
          sbData.Append(",");
          sbData.Append("\"");
          sbData.Append(RemoveSpecialCharacters(obj.ToString()));
          sbData.Append("\"");
     }
 }
 //Write to file
 writer.WriteLine(sbData.ToString());
 writer.close();//may use using 
 //after writing insert into database table.
 SQLHelper.MoveOtherQuotesToWaitingArivalOfBags(quoteHeaderId, Config.WSUserName, refCode);

}

Upvotes: 1

Related Questions