0

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

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 命令。

4

1 回答 1

2

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

由于您正在尝试运行mklink内置的,cmd因此您需要使用:

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

文档状态:

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

进而:

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

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

于 2018-05-15T04:22:23.997 回答