Capture Stored Procedure print output in .NET

C#.NetStored Procedures

C# Problem Overview


Is it possible to capture print output from a T-SQL stored procedure in .NET?

I have a lot of legacy procs that use the print as means of errorMessaging. An example, is it possible to access the outprint 'word' from following PROC?

-- The PROC
CREATE PROC usp_PrintWord AS
 	PRINT 'word'

// Some C# Code to would like to pull out 'word'
SqlCommand cmd = new SqlCommand("usp_printWord", TheConnection);
cmd.CommandType = CommandType.StoredProcedure;
// string ProcPrint = ???

C# Solutions


Solution 1 - C#

You can do this by adding an event handler to the InfoMessage event on the connection.

myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);

void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    myStringBuilderDefinedAsClassVariable.AppendLine(e.Message);
}

Solution 2 - C#

This is really handy if you want to capture Print output in LinqPad's output console:

SqlConnection conn = new SqlConnection(ConnectionString);
//anonymous function to dump print statements to output console
conn.InfoMessage += (object obj, SqlInfoMessageEventArgs e)=>{
    			e.Message.Dump();
    		};

Solution 3 - C#

To get the output into a variable:

string printOutput = "";

using (var conn = new SqlConnection(...))
{
    // handle this event to receive the print output
    conn.InfoMessage += (object obj, SqlInfoMessageEventArgs e) => {
        printOutput += e.Message;
    };

    // execute command, etc.
}

Console.Write(printOutput);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - C#AdaTheDevView Answer on Stackoverflow
Solution 2 - C#BraveNewMathView Answer on Stackoverflow
Solution 3 - C#KeithView Answer on Stackoverflow