代码之家  ›  专栏  ›  技术社区  ›  Snake Eyes

在C中用进程执行dotnet命令#

c#
  •  0
  • Snake Eyes  · 技术社区  · 6 年前

    我有以下C行代码,其中打开进程并运行dotnet命令以打开我的控制台应用程序(使用.net standard/core创建)

    var args = new Dictionary<string, string> {
     { "-p", "title"},
     { "-l", "games"},
     ...
    };
    
    var arguments = string.Join(" ", args.Select((k) => string.Format("{0} {1}", k.Key, "\"" + k.Value + "\"")));
    
    var dllPath = @"C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll";
    ProcessStartInfo procStartInfo = new ProcessStartInfo();
    procStartInfo.FileName = "C:\....\cmd.exe";
    procStartInfo.Arguments = $"dotnet \"{dllPath}\" {arguments}";
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = false;
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.RedirectStandardError = true;
    
    StringBuilder sb = new StringBuilder();
    Process pr = new Process();
    pr.StartInfo = procStartInfo;
    
    pr.OutputDataReceived += (s, ev) =>
    {
        if (string.IsNullOrWhiteSpace(ev.Data))
        {
            return;
        }
    
        string[] split = ev.Data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        int.TryParse(split[split.Length - 1], out output);
    };
    
    pr.ErrorDataReceived += (s, err) =>
    {
        // do stuff here
    };
    
    pr.EnableRaisingEvents = true;
    pr.Start();
    pr.BeginOutputReadLine();
    pr.BeginErrorReadLine();
    
    pr.WaitForExit();
    

    Arguments 结果是:

    dotnet "C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll" -p "title" -l "games" -s "" -r "none" -k "0" -d "/path/" -f ""
    

    ev.Data OutputDataReceived 事件看起来像:

    Microsoft Windows [Version 10.0.16299.665]
    (c) 2017 Microsoft Corporation. All rights reserved.
    

    就这样。。。

    我希望对dll运行dotnet命令。

    如果我手动运行result命令 dotnet .... 上面,工作正常。但不是我的密码。为什么?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Access Denied    6 年前

    因为cmd返回:

    Microsoft Windows [Version 10.0.16299.665] 
    (c) 2017 Microsoft Corporation. All rights reserved.
    

    你需要打电话

    procStartInfo.FileName = "dotnet"