Process.Start()System.dll中发生'System.ComponentModel.Win32Exception'

时间:2017-05-19 09:24:27

标签: c# wpf

我试图订阅process.OutputDataReceived。看不到结果(事件没有在输出上触发)我在Msdn上跟随了一个例子。但是process.BeginOutputReadLine();给了我例外。我尝试运行的过程是一个简单的批处理文件命令wmic product where "Name like '%%Microsoft Visual C++ %%'" get Name, Version足够process.Exited事件正常工作。

这是代码

  void DoSomething(object sendingProcess, DataReceivedEventArgs outLine)
    {
        Application.Current.Dispatcher.Invoke(new Action(() => { textBox.Text = outLine.Data; }));
    }
    public MainWindow()
    {
        InitializeComponent();

        string batPath = @"..\..\WMIC batch\";

        var process = new Process();

        process.StartInfo.WorkingDirectory = batPath;
        process.StartInfo.FileName = "Redistributable_Packages_Check.bat";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;

        process.EnableRaisingEvents = true;
        process.Exited += new EventHandler(Process_Exited);

        process.OutputDataReceived +=new DataReceivedEventHandler(DoSomething);

        process.StartInfo.RedirectStandardInput = true;
        process.Start();

        StreamWriter sortStreamWriter = process.StandardInput;
        process.BeginOutputReadLine();

        //textBox.Text = "Initialised";



    }

    private void Process_Exited(object sender, EventArgs e)
    {
        Application.Current.Dispatcher.Invoke(new Action(() => { textBox.Text = "Process has exited"; }));
    }

异常详细信息{“系统找不到指定的文件”}

P.S省略行

  process.StartInfo.UseShellExecute = false;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.RedirectStandardInput = true;

触发批处理文件。所以我相信它可以找到该文件。

1 个答案:

答案 0 :(得分:0)

我创建了一个像你一样的小例子,发现原因确实(如评论中提到的mm8)你需要为process.StartInfo.FileName指定完整路径。仅设置WorkingDirectory

是不够的

例如:

process.StartInfo.WorkingDirectory = batPath;
process.StartInfo.FileName = System.IO.Path.Combine(batPath, "Redistributable_Packages_Check.bat");

WorkingDirectory仅指定新进程使用的相对文件名所涉及的路径。但FileName仍然与您当前进程的工作目录相关。