Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
DotNETFrameworkNotesForProfessionals.pdf
Скачиваний:
32
Добавлен:
20.05.2023
Размер:
1.82 Mб
Скачать

Chapter 52: Write to and read from StdErr stream

Section 52.1: Write to standard error output using Console

var sourceFileName = "NonExistingFile"; try

{

System.IO.File.Copy(sourceFileName, "DestinationFile");

}

catch (Exception e)

{

var stdErr = Console.Error;

stdErr.WriteLine($"Failed to copy '{sourceFileName}': {e.Message}");

}

Section 52.2: Read from standard error of child process

var errors = new System.Text.StringBuilder(); var process = new Process

{

StartInfo = new ProcessStartInfo

{

RedirectStandardError = true, FileName = "xcopy.exe",

Arguments = "\"NonExistingFile\" \"DestinationFile\"", UseShellExecute = false

},

};

process.ErrorDataReceived += (s, e) => errors.AppendLine(e.Data); process.Start();

process.BeginErrorReadLine(); process.WaitForExit();

if (errors.Length > 0) // something went wrong

System.Console.Error.WriteLine($"Child process error: \r\n {errors}");

GoalKicker.com – .NET Framework Notes for Professionals

163