How to pass more arguments to Sqlbulkcopy notifyafter

c# sql sqlbulkcopy sql-server

Question

I am invoking a notifier while doing the sqlbulkcopy. As of now I am only printing the number of rows that are written to the DB. I would like to print other arguments like the DB name, current timestamp, etc.. can someone please let me know how to do this.

Popular Answer

You can't provide arguments to the event handler, but you can use a delegate that captures as much local information as you like:

using (var bulkCopy = new SqlBulkCopy(...)) {
    string database = "myDatabase";
    bulkCopy.SqlRowsCopied += (o, e) => {
        Console.WriteLine(
            "Time: {0}, database: {1}, rows copied: {2}", 
            DateTime.Now, database, e.RowsCopied
        );
    };
    bulkCopy.WriteToServer(...);
}   

You can make this generic by wrapping it in a method and using the method arguments instead of local variables. You can also wrap SqlBulkCopy itself and create your own event with a custom EventArgs, but for the information you're adding, that doesn't seem to be worth it.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why