Search code examples
c#fileprocessshared

Run exe file while it is still open in C#


Currently I do the following:

  1. Include an EXE file in resource file.
  2. in runtime I extract EXE file and write it to a file on HDD, with "DeleteOnClose" option.
  3. Obviously II do not close the file so it remains on Disk.
  4. I go to path and double click it , but it refuses to open.
  5. if I use "Process.Start" I get file not exist error although it is there in the given path.
  6. I set FileShare and FileAccess to ReadWrite.
  7. Again Process.Start doesn't work.

Here is the code I use:

byte[] exeFile =ExeSecure.Properties.Resources.ReqCheck;
//2) Create file to be deleted on close
FileStream aFile = new FileStream(@"c:\reco.exe", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 20000, FileOptions.DeleteOnClose);
//3) Write Exe file content to HDD
aFile.Write(exeFile, 0, exeFile.Length);
aFile.Flush();
Thread.Sleep(100); //Wait a while for file to be flushed
while (!File.Exists(@"c:\reco.exe")); //Make sure file is there on HDD
    Process.Start("C:\reco.exe");//Start file , this always fails.

Solution

  • Maybe this is just a typo in your question, but the path in Process.Start is incorrect. You are missing the @ sign:

    Process.Start(@"C:\reco.exe");