Exception using Process.Start() and Windows Task Scheduler

不羁岁月 提交于 2021-02-17 04:31:32

问题


I wrote C# console app that at some point tries to unzip a file using 7zip (specifically 7za.exe). When I run it manually everything runs fine, but I if I setup a task in Task Scheduler and have it run it throws this exception:

System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)

Here's my code:

ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "7za.exe";         //http://www.dotnetperls.com/7-zip-examples
p.Arguments = "x " + zipPath + " -y -o" + unzippedPath;
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();

7za.exe is part of my project, with Copy to Output Directory = Copy Always. The task is setup with my account, and I checked off Run with Highest Privileges.


回答1:


It looks like you are relying on the working directory being the directory that contains the executable. And that is not necessarily the case. Instead of

p.FileName = "7za.exe";

specify the full path to the 7za executable. Construct this path by dynamically retrieving the directory which holds your executable at runtime. For example by using Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).

So your code might become

p.FileName = Path.Combine(
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), 
    "7za.exe"
);


来源:https://stackoverflow.com/questions/25245057/exception-using-process-start-and-windows-task-scheduler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!