-1

I have two text files in a folder, two datatables, and two tables in db. Each file goes into a datatable and eventually gets inserted into their table in the db, all that is working properly, however I am trying to set it up where if an insert fails the files don't get processed. I've been fiddling around with try catch, however I've not been able to get it to work, it seems when there is an error one the text files gets processed and populated in the table.

foreach file enumerate folder
{

if (folder path contains file1)

try
{

     fill datatable

     insert into database
}

catch {}


else if (folder path contains file2)

try
{

     fill datatable

     insert into database
}

catch {}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user406151
  • 395
  • 3
  • 9
  • 15
  • 1
    Look up Transactions at the database end, execute your insert statements in a [TransactionScope](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope%28v=vs.110%29.aspx) and in case of exception roll back everything. – Habib Jan 20 '15 at 16:16
  • 1
    Catching exceptions and ignoring the exception object is possible the worst thing to do when trying to figure out what causes an error. – Uwe Keim Jan 20 '15 at 16:16
  • that is just the logic, the exceptions are being caught. – user406151 Jan 20 '15 at 16:20
  • Please provide a simple example of what are you _actually_ doing. From your example it is not clear how or where your files get processed. – smiech Jan 20 '15 at 16:45

1 Answers1

1

If I've understood the question then the code below may help:

bool databaseUpdatedSuccessfully = false;

using (var Conn = new SqlConnection(_ConnectionString))
{
    try
    {
        Conn.Open();
        using (var ts = new System.Transactions.TransactionScope()) {
            using (SqlCommand Com = new SqlCommand(ComText, Conn))
            {
                // db work
            }
            ts.Complete();
            databaseUpdatedSuccessfully = true;
        }
    }
    catch (Exception Ex)
    {     
        // log exception
    }
}
if (databaseUpdatedSuccessfully)
{
    // process files !
}

Code above adapted from the accepted answer to another transaction question.

Community
  • 1
  • 1
jonnarosey
  • 520
  • 1
  • 8
  • 19
  • I think you should have a finally { } block as well, to verify the transaction is rolled back and closed if an exception occurs. – Paul Jan 20 '15 at 17:51
  • I don't think there is a good reason for a finally block in this instance, we can trust the "using ... TransactionScope" to handle rolling back and closing should something go wrong. – jonnarosey Feb 10 '15 at 14:14