【问题标题】:I'm having exception errors, file not found我遇到异常错误,找不到文件
【发布时间】:2018-10-24 19:31:25
【问题描述】:

当我尝试运行此功能时,它会在进程启动时不断崩溃。

public static void MapDestinationToSource (string destination, string source)
{
    System.Diagnostics.Process proc = new System.Diagnostics.Process ();
    // set the file to execute
    proc.StartInfo.FileName = "mklink";
    proc.StartInfo.Arguments = $"/D \"{source}\" \"{destination}\"";
    // Redirect the output stream of the child process.
    proc.StartInfo.UseShellExecute = true;
    //proc.StartInfo.RedirectStandardOutput = true;
    // start the process
    proc.Start ();
    // Do not wait for the child process to exit before
    // reading to the end of its redirected stream.
    // p.WaitForExit();
    // Read the output stream first and then wait.
    string output = proc.StandardOutput.ReadToEnd ();
    proc.WaitForExit ();
}

例外:

System.ComponentModel.Win32Exception occurred
  HResult=0x80004005
  Message=The system cannot find the file specified
  Source=System
  StackTrace:
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at GameCloud.StorageLibrary.MapDestinationToSource(String destination, String source) in D:\Development\code\sample\server\ClientAgent\ClientAgent\StorageLibrary.cs:line 130
   at GameCloud.Program.Main(String[] args) in D:\Development\code\sample\server\ClientAgent\ClientAgent\Program.cs:line 135

当我在命令行上执行命令时,它可以工作。但它没有在代码中。我已经设置了安全策略以允许当前用户在没有提升访问权限的情况下执行 mklink 命令。

【问题讨论】:

标签: c# mklink


【解决方案1】:

如果您尝试执行可执行程序 (bob.exe),请查看下面我删除的答案。

由于您尝试运行mklink,它内置于cmd,那么您需要使用:

proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = $"/C mklink /D \"{source}\" \"{destination}\"";

The docsstate:

当 UseShellExecute 为 true 时,WorkingDirectory 属性指定 可执行文件的位置。如果 WorkingDirectory 为空 字符串,假设当前目录包含 可执行文件。

然后:

当 UseShellExecute 为 false 时,FileName 属性可以是 可执行文件的完全限定路径,或简单的可执行文件名称 系统将尝试在指定的文件夹中查找 PATH 环境变量。

因此,您需要将UseShellExecute 设置为false(以便您的PATH 用于查找可执行文件)WorkingDirectory 设置为包含可执行文件。

【讨论】:

猜你喜欢
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多