Let's say I have contents of an executable (or a bat script, doesn't matter) in memory and want to run it as a new process. That is easy.
File.WriteAllBytes(filePath, contents);
// gap
Process.Start(filePath)
But I want to make sure that the executed file is not tampered by any other process. And there is a gap between file creation and execution. It gives a chance to tamper the file with the right tools.
So, instead of File.WriteAllBytes
, I went with opening a FileStream FileShare.Read
and keeping it open until the execution has finished.
using(var fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
{
Process.Start(filePath)
}
But this doesn't work. Process.Start
fails with:
System.ComponentModel.Win32Exception (32): The process cannot access the file because it is being used by another process.
This question and its answer explains why I think. In a nutshell, Process.Start
will attempt to open the file with FileShare.Read
and fail because the open FileStream already has Write Access, hence failing the FileShare.Read
attempt of the process.
Is there a way to do this cleanly?
A workaround I can think of is to save the file, close it, open a new FileStream with FileShare.Read
and FileAccess.Read
, make sure the content is still the same before executing it. But that's not pretty.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…