C# 在函数外部使用StreamWriter或Stream
我需要创建一个函数,从process.StandardInput向流发送命令。无法初始化写入程序时出现错误。我怎样才能解决这个问题C# 在函数外部使用StreamWriter或Stream,c#,process,stream,iostream,streamwriter,C#,Process,Stream,Iostream,Streamwriter,我需要创建一个函数,从process.StandardInput向流发送命令。无法初始化写入程序时出现错误。我怎样才能解决这个问题 private StreamWriter writer; private static void SendProcessCmd(string cmd) { writer.WriteLine(cmd); } public static void CreateProcess() { ProcessStartInfo processInfo = new
private StreamWriter writer;
private static void SendProcessCmd(string cmd)
{
writer.WriteLine(cmd);
}
public static void CreateProcess()
{
ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardInput = true;
try
{
using (Process process = Process.Start(processInfo))
{
writer = new StreamWriter(process.StandardInput.BaseStream);
//writer = process.StandardInput;
while (true)
{
String strInput = Console.ReadLine();
writer.WriteLine(strInput);
}
process.WaitForExit();
}
}
}
没有你得到的具体错误,这是我对问题的最好猜测 您正在创建一个成员变量private StreamWriter writer,然后尝试在静态方法中访问它。尝试将StreamWriter设置为静态 此外,您还有一个try block,但没有捕获或最终捕获。要么完全删除try,要么使用catch块添加一些错误处理
最后一件事,我不确定您想要完全完成什么,但我强烈建议您添加一种打破while循环的方法。实际上,它保证是一个无限循环。您到底遇到了什么问题?我认为你的代码甚至无法编译。然而,你真的无法摆脱它。大胆的举动:哎哟!!这太粗鲁了,不停地要求用户进入控制台而不中断。好吧,我的印象是,如果我将其设置为静态,我就无法从函数中为其设置值。有一个catch块,while循环只是暂时的测试。我把代码精简了很多,这样更容易阅读。