使用Process.Start()和Windows Task Scheduler的异常 [英] Exception using Process.Start() and Windows Task Scheduler

查看:129
本文介绍了使用Process.Start()和Windows Task Scheduler的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了C#控制台应用程序,该应用程序有时试图使用7zip(特别是7za.exe)解压缩文件.当我手动运行它时,一切运行正常,但是如果我在Task Scheduler中设置任务并运行它,则会抛出此异常:

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)

这是我的代码:

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是我项目的一部分,其中 Copy to Output Directory = Copy Always .该任务已使用我的帐户进行设置,然后我选中了以最高特权运行.

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.

推荐答案

似乎您所依赖的工作目录是包含可执行文件的目录.并不一定是这种情况.代替

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";

指定7za可执行文件的完整路径.通过动态检索在运行时保存可执行文件的目录来构造此路径.例如,通过使用 Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).

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"
);

这篇关于使用Process.Start()和Windows Task Scheduler的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆