C
C#3y ago
HimmDawg

❔ Process.Exited immediately fired if corresponding app is already opened

I wrote a function that downloads a PDF from some API and then attempts to open it. For this reason, I save the pdf in a tmp file and then use Process to open the default app for it - in this case Adobe Acrobat Reader. The code looks like this
string tmpFilePath = File.Exists($"{Path.GetTempPath()}{pdfFile}")
? $"{Path.GetTempPath()}{Environment.TickCount}_{pdfFile}"
: $"{Path.GetTempPath()}{pdfFile}";

Process p = new Process();
p.StartInfo.FileName = tmpFilePath;
p.EnableRaisingEvents = true;
p.Exited += (s, e) =>
{
p.WaitForExit();
if (File.Exists(tmpFilePath))
{
File.Delete(tmpFilePath);
p.Close();
}
};
p.Start();
string tmpFilePath = File.Exists($"{Path.GetTempPath()}{pdfFile}")
? $"{Path.GetTempPath()}{Environment.TickCount}_{pdfFile}"
: $"{Path.GetTempPath()}{pdfFile}";

Process p = new Process();
p.StartInfo.FileName = tmpFilePath;
p.EnableRaisingEvents = true;
p.Exited += (s, e) =>
{
p.WaitForExit();
if (File.Exists(tmpFilePath))
{
File.Delete(tmpFilePath);
p.Close();
}
};
p.Start();
The problem occures when Acrobat Reader is opened before I download the PDF. For some reason, the Exited event is immediately fired when I try to open the file. But then I get an error on the line File.Delete saying that the file is already in use (presumably by the acrobat reader). Not sure what the "best practice" is to handle Process the right way here fluffyFoxThink
2 Replies
cap5lut
cap5lut3y ago
basically the newly spawned process will just tell the already running process to handle the pdf file. u would need to get the already running process (https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocesses?view=net-7.0) and call WaitForExit() on that instance
Process.GetProcesses Method (System.Diagnostics)
Creates an array of new Process components and associates them with existing process resources.
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?