【问题标题】:Exception using Process.Start() and Windows Task Scheduler使用 Process.Start() 和 Windows 任务计划程序的异常
【发布时间】:2014-08-11 13:57:14
【问题描述】:

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

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。该任务是使用我的帐户设置的,我检查了Run with Highest Privileges

【问题讨论】:

  • 计划任务将在路径上看不到7za.exe 的不同配置文件下运行。或者,工作目录不是您所期望的。指定完整路径可能是一个不错的举措。不知道为什么要以高权限运行。你为什么这样做,或者这只是随机试验和错误?
  • @DavidHeffernan 是的,正在尝试最高权限,看看它是否有所作为。因此,如果它在不同的配置文件下运行,我是否只需指定 7za.exe 的完整路径,然后它应该运行?

标签: c# scheduled-tasks console-application


【解决方案1】:

看起来您依赖工作目录作为包含可执行文件的目录。情况不一定如此。而不是

p.FileName = "7za.exe";

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

所以你的代码可能会变成

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2014-12-28
    • 1970-01-01
    相关资源
    最近更新 更多