Use StreamWriter or Stream outside of Function
I need to make a function to send commands to the Stream from process.StandardInput. I am having an error with the writer not be initial开发者_开发知识库ized. How can I fix this?
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();
}
}
}
Without the specific error you are getting this is my best guess as to the problem.
You are creating an member variable private StreamWriter writer
and then trying to access it inside static
methods. Try making StreamWriter writer
static.
Also, you have a try
block, but no catch
or finally
. Either remove the try
completely or add in some error handling with a catch
block.
One last thing, I'm not sure what you are trying to accomplish completely, but I would strongly suggest that you add a way to break out of your while loop. As it is, it is guaranteed to be an infinite loop.
精彩评论