[英]“The process cannot access the file because it is being used by another process” c#
我想使用 c#、output 中的进程运行exe
文件,当我运行 exe 文件时,它将是按键上按下的字符的字符串,并将使用RedirectStandardOutput = true
打印到进程中。 我将接收一个包含文件的byte[]
并将其转换为文件,然后创建一个将激活文件的新进程,我的意图是从文件中读取(键盘按下的字符串/字符)和在TB
中看到它,它是一个 TextBlock(我正在研究 WPF)。 但是当我运行它时,它会打印上面提到的 excaption。 这是我的代码:
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");
在这里,您正在打开 stream。 这个永远不会关闭。 因此,当您稍后尝试访问它时,它将已经在使用中并且无法打开。 您需要通过在用法周围包装 using 语句或在完成文件处理后添加 file.Close() 来关闭它。
using (var file = File.Create("p.exe"))
{
}
或者
file.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.