Мне нужно написать компонент для приложения, которое тесно взаимодействует с приложением командной строки. Приложение командной строки задает серию вопросов, выполняет некоторые вычисления, а затем завершает свою работу (что мне нужно определить). По сути, я хочу завершить это взаимодействие в классе-оболочке.
Добивался ли кто-нибудь подобное в прошлом? Если да, то как вы это сделали? Вы заметили шаблон или, может быть, какую-нибудь хорошую сборку классов для использования? Ваше здоровье!





Вам нужно будет перенаправить как входной, так и выходной потоки, используя Process; обрабатывать и то и другое немного сложнее, так как нужно быть осторожным, чтобы что-то не потерялось в буферах (вызывая тупик).
Вы также можете посмотреть OutputDataReceived для ответов на основе событий.
Если все приложения разрабатываются в dotnet, вы можете использовать Класс сборки
Меня раздражает, когда мои ответы - это просто ссылки на что-то еще. Я не понимаю, где мне очень помогает ссылка на статью C# Corner.
Вопросу сегодня 10 лет, но его следовало прояснить. В вопросе не указывается, есть ли окончания строк (CrLf) в конце каждого вопроса. Предполагая, что они есть, как показано ниже:
string Answer;
Console.Out.WriteLine("First question: ");
Answer = Console.In.ReadLine();
Console.Out.WriteLine("Another question: ");
Answer = Console.In.ReadLine();
Console.Out.WriteLine("Final question: ");
Answer = Console.In.ReadLine();
Тогда для ответа на него можно использовать следующее:
class Program
{
const string FirstQuestion = "First question: ";
const string SecondQuestion = "Another question: ";
const string FinalQuestion = "Final question: ";
static AutoResetEvent Done = new AutoResetEvent(false);
static void Main(string[] args)
{
const string TheProgram = @" ... ";
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo(TheProgram);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
p.StartInfo = psi;
Console.WriteLine("Executing " + TheProgram);
p.Start();
DoPromptsAsync(p);
Done.WaitOne();
}
private static async Task DoPromptsAsync(Process p)
{
StreamWriter sw = p.StandardInput;
StreamReader sr = p.StandardOutput;
string Question;
Question = await sr.ReadLineAsync();
if (Question != FirstQuestion)
return;
sw.WriteLine("First answer");
Console.WriteLine(Question + "answered");
Question = await sr.ReadLineAsync();
if (Question != SecondQuestion)
return;
sw.WriteLine("Second answer");
Console.WriteLine(Question + "answered");
Question = await sr.ReadLineAsync();
if (Question != FinalQuestion)
return;
sw.WriteLine("Final answer");
Console.WriteLine(Question + "answered");
Done.Set();
}
}
Следующее работает в приложении WPF; Я использовал событие двойного щелчка для тестирования, но его можно было использовать в других событиях WPF.
const string TheProgram = @" ... ";
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo(TheProgram);
psi.UseShellExecute = false;
//psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
p.StartInfo = psi;
p.Start();
const string FirstQuestion = "First question: ";
const string SecondQuestion = "Another question: ";
const string FinalQuestion = "Final question: ";
StreamWriter sw = p.StandardInput;
StreamReader sr = p.StandardOutput;
string Question;
StringBuilder sb = new StringBuilder("Executing " + TheProgram + "\r\n");
Question = await sr.ReadLineAsync();
if (Question != FirstQuestion)
return;
sw.WriteLine("First answer");
sb.Append(Question + "answered\r\n");
Question = await sr.ReadLineAsync();
if (Question != SecondQuestion)
return;
sw.WriteLine("Second answer");
sb.Append(Question + "answered\r\n");
Question = await sr.ReadLineAsync();
if (Question != FinalQuestion)
return;
sw.WriteLine("Final answer");
sb.Append(Question + "answered\r\n");
ResultBox.Text = sb.ToString();
Думаю, будет сложнее, если после каждого вопроса не будет конца строки.