I want to run an exe
file using process in c#, the output when i will run the exe file will be the string of the char pressed on the keyboerd and it will be printed to the process using RedirectStandardOutput = true
. i will recive a byte[]
that contains the file and will convert it to file, then make a new process that will activate the file and my intention is to read the out from the file(the string/char pressed by the keyboerd) and see it in the TB
which is a TextBlock(I'm working on WPF). but when i run it it print the excaption mentioned above. here is my code:
private void p1()
{
byte[] b1 = the byte[] containing the file;
FileStream file = File.Create("p.exe");
file.Write(b1, 0, b1.Length);
try
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = file.Name,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
Thread t = new Thread(() => { res = ReadFromP(process); });
t.Start();
t.Join();
TB.Text=res;
}
catch
{
TB.text="didnt worked";
}
}
private string ReadFromP(Process p)
{
try
{
string line;
p.Start();
// while (!p.StandardOutput.EndOfStream)
//{
line = p.StandardOutput.ReadLine();
//}
return line;
//p.WaitForExit();
}
catch (Exception e)
{
return(e.Message);
}
}
FileStream file = File.Create("p.exe");
Here you are opening a stream. This one is never closed. So when you are trying to access it at a later point it will be already in use and cannot be opened. You need to close it by either wrapping a using statement around the usage or add file.Close() when you are done working with the file.
using (var file = File.Create("p.exe"))
{
}
or
file.Close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.