如何通过 .NET Core 重定向 sqlpackage StdError 流

问题描述 投票:0回答:0

我需要从 C# .NET 7 应用程序调用

SqlPackage
,我通过创建一个
System.Diagnostics.Process
来实现。我的示例代码可以在下面找到。

我可以运行命令,但是如果我遇到的命令没有错误,每当我重定向 stdError 时

发生意外故障:句柄无效..

但是如果命令有错误,我会得到相应的错误信息。

如果我想提供一个 valid 命令,我必须删除 StdError 重定向,以便我接收 stdOutput 的内容。

为什么我在这种情况下收到无效的句柄错误没有错误从stdError重定向但是当有错误重定向到stdError时它工作正常?如果可能的话,我怎样才能解决这个问题,以便我可以从命令行看到输出和可能的错误。

using System.Diagnostics;

var processStartInfo = new ProcessStartInfo
{
    FileName = @"sqlpackage.exe", // Replace with your command or executable
    // Arguments = "/a:Import /tcs:\"Data Source=foo;Initial Catalog=bar;User Id=sa;Password=Passw0rd" /sf:backup.bacpac /p:DatabaseEdition=Premium /p:DatabaseServiceObjective=P4", // Invalid command to test stdError working with an invalid command
    Arguments = "/help", // Does not work if stdError is redirected
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false,
    CreateNoWindow = true
};

// Create and start the process
using var process = new Process
{
    StartInfo = processStartInfo,
    EnableRaisingEvents = true
};

// Set up a single event handler for both output and error streams
process.OutputDataReceived += (sender, eventArgs) =>
{
    if (!string.IsNullOrEmpty(eventArgs.Data))
    {
        Console.WriteLine(eventArgs.Data);
        // You can log the output to a file or another logging mechanism here
    }
};

// Set up a single event handler for both output and error streams
process.ErrorDataReceived += (sender, eventArgs) =>
{
    if (!string.IsNullOrEmpty(eventArgs.Data))
    {
        Console.WriteLine(eventArgs.Data);
        // You can log the output to a file or another logging mechanism here
    }
};

// Start the process and begin reading the output asynchronously
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();

// Wait for the process to finish
process.WaitForExit();

Console.WriteLine("Process completed with exit code: " + process.ExitCode);
c# .net-core command-line-interface sqlpackage
© www.soinside.com 2019 - 2024. All rights reserved.