使用SqlInfoMessageEventHandler将存储过程输出写入文件

时间:2019-01-07 14:00:27

标签: c# sql-server

我有一个存储过程可以打印到SQL Server中的Messages,我正在编写一个C#应用程序来调用该存储过程并将输出写入文件中。

我正在使用SqlInfoMessageEventHandler处理消息中的输出,但是输出,在这种情况下,结果变量未写入文件中。

下面是我为此应用程序提供的完整代码。

public class SProc
{
    public static string result;

    static void Conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
    {
        result = (e.Message);
    }

    static void Main(string[] args)
    {
        string ClassName = "";
        string TableName = "";

        Console.WriteLine("Enter Class Name: ");
        ClassName = Console.ReadLine();
        Console.WriteLine("Enter Table Name: ");
        TableName = Console.ReadLine();

        var filePath = @"C:\Temp\%name%.txt".Replace("%name%", ClassName); 

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionVal"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("dbo.mainproc", connection))
            {
                connection.Open();
                cmd.CommandText = "dbo.mainproc";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@tableName", "model");

                cmd.ExecuteNonQuery();

                connection.InfoMessage += new SqlInfoMessageEventHandler(Conn_InfoMessage);
                connection.Close();
            }
        }

        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                */Outputs just fine*/
                sw.WriteLine($"[Table({TableName})]");
                 */Returns Empty in text file */
                sw.WriteLine($"{result}")
            }
         }
    }
}

0 个答案:

没有答案