数据表和尝试捕获逻辑

Datatable and try catch logic

我在一个文件夹中有两个文本文件,两个数据table,在数据库中有两个table。每个文件都进入数据 table 并最终被插入到数据库中的 table 中,所有这些都正常工作,但是我正在尝试将其设置为如果插入失败则文件不会得到处理。我一直在摆弄 try catch,但是我无法让它工作,似乎当出现错误时,文本文件被处理并填充到 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 {}

如果我理解了这个问题,那么下面的代码可能会有所帮助:

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 !
}

上面的代码改编自 another transaction question.

的已接受答案