无法使用ProcessStartInfo运行cmd.exe

时间:2015-03-12 18:15:23

标签: c# json cmd

Web.config:

<appSettings>
    <add key="MystemDirectory" value="D:\mystem\"/>
</appSettings>

控制器:

if (flag)
{
    db.FbDocuments.Add(fbDocument);
    db.SaveChanges();

    var workingDirectory = WebConfigurationManager.AppSettings["MystemDirectory"];
    System.IO.File.WriteAllText(workingDirectory + @"\input.txt", fbDocument.Title);
    Process process = new Process();
    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processStartInfo.FileName = "cmd.exe";
    processStartInfo.WorkingDirectory = workingDirectory;
    processStartInfo.Arguments = "mystem.exe --format json input.txt output.txt";
    process.StartInfo = processStartInfo;
    process.Start();
    string text = System.IO.File.ReadAllText(workingDirectory + @"\output.txt");
    var jsSerializer = new JavaScriptSerializer();
    var jsonCleanText = jsSerializer.Deserialize<CleanText>(text);

    var fbToUpdate = db.FbDocuments.FirstOrDefault(x => x.Id == fbDocument.Id);
    fbToUpdate.CleanText = jsonCleanText.ToString();
    db.SaveChanges();
}

当控制器中的代码将文本写入input.txt时,但output.txt仍为空。如果手动运行cmd.exe,一切正常......在文件input.txt output.txt之后并保持填充状态,如果再次在控制器中运行代码,则变量jsonCleanText中的错误格式无效JSON和output.txt值不会改变。

1 个答案:

答案 0 :(得分:0)

试试这个

            if (flag)
                    {
                        db.FbDocuments.Add(fbDocument);
                        db.SaveChanges();

                        var workingDirectory = WebConfigurationManager.AppSettings["MystemDirectory"];
                        System.IO.File.WriteAllText(workingDirectory + @"\input.txt", fbDocument.Title);
                        Process process = new Process();
                        ProcessStartInfo processStartInfo = new ProcessStartInfo();
                        processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        processStartInfo.FileName = "mystem.exe";
                        processStartInfo.WorkingDirectory = workingDirectory;
                        processStartInfo.Arguments = "--format json input.txt output.txt";
                        process.StartInfo = processStartInfo;
                        process.Start();
                        string text = System.IO.File.ReadAllText(workingDirectory + @"\output.txt");
                        var jsSerializer = new JavaScriptSerializer();
                        var jsonCleanText = jsSerializer.Deserialize<CleanText>(text);

                        var fbToUpdate = db.FbDocuments.FirstOrDefault(x => x.Id == fbDocument.Id);
                        fbToUpdate.CleanText = jsonCleanText.ToString();
                        db.SaveChanges();

                    }