【发布时间】:2019-10-22 12:22:28
【问题描述】:
我的 (visual studio) 预构建操作调用可执行文件时遇到问题,该操作需要控制台输入。
代码如下:
using System;
using System.Diagnostics;
using System.Text;
namespace MyMinumumExample
{
internal class MinimumExample
{
private StringBuilder stdOutput = null;
private readonly string assemblyFilePath;
private readonly Process gitProcess = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "git",
RedirectStandardOutput = true,
UseShellExecute = false,
},
};
public MinimumExample(string path)
{
assemblyFilePath = path;
}
private static int Main(string[] args)
{
string path = args[0];
var program = new MinimumExample(path);
if (program.CheckIfFileIsDirty(path))
{
Console.WriteLine("Changes will be discarded after compiling. Do you want to proceed?");
while (true)
{
Console.Write("[y/n]: ");
ConsoleKeyInfo key = Console.ReadKey();
if (key.KeyChar == 'y')
break;
if (key.KeyChar == 'n')
return 1;
Console.WriteLine();
}
}
return 0;
}
private bool CheckIfFileIsDirty(string path)
{
string gitCmdArgs = string.Format("diff --shortstat -- {0}", path);
stdOutput = new StringBuilder();
gitProcess.StartInfo.Arguments = gitCmdArgs;
gitProcess.Start();
gitProcess.BeginOutputReadLine();
gitProcess.OutputDataReceived += GitProcessOutputHandler;
gitProcess.WaitForExit();
gitProcess.OutputDataReceived -= GitProcessOutputHandler;
if (gitProcess.ExitCode != 0) throw new Exception(string.Format("Process 'git {0}' failed with code {1}", gitCmdArgs, gitProcess.ExitCode));
return !string.IsNullOrWhiteSpace(stdOutput.ToString());
}
private void GitProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!string.IsNullOrWhiteSpace(outLine.Data))
{
stdOutput.Append(outLine.Data);
}
}
}
}
如果我从 cmd-shell 或批处理文件运行它,一切正常。如果我将它放入预构建操作中,我会在第 38 行得到一个例外:
ConsoleKeyInfo key = Console.ReadKey();
预构建操作如下所示:
call $(SolutionDir)MinimumExample.exe $(ProjectDir)dirtyExampleFile.cs
IF %ERRORLEVEL% GTR 0 (
EXIT 1
)
如果我用start <exe> 调用可执行文件,示例可以工作,但我没有得到 exe 的退出代码(但可能是新的 cmd shell)。
或者,我可以获取 cmd shell 的退出代码来验证可执行文件是否干净地退出,或者我可以找到从构建事件控制台读取键盘输入的方法。
有没有人有想法,如何解决这个问题?
提前致以最诚挚的问候和感谢!
【问题讨论】:
-
在构建操作中执行之前,您是否尝试过
echo y|?它模拟为Console.ReadKey();键入y
标签: c# visual-studio batch-file pre-build-event