【问题标题】:C# - Running a CMD command within a Program.C# - 在程序中运行 CMD 命令。
【发布时间】:2012-05-19 01:55:56
【问题描述】:

我在此程序中运行 CMD 命令时遇到问题。我正在使用“lua LuaSrcDiet.lua myscript.lua -o myscriptdone.lua”命令。每当我运行程序时,它都会告诉我找不到指定的文件。我猜这是因为命令提示符在运行时不在正确的目录中。正确的目录是用户文件夹。你有什么办法可以让我解决这个问题。非常感谢。

try 
{
    File.Copy(filedir1, userPath + "/myscript.lua", true);
}
catch
{
    MessageBox.Show("There has been an problem. It may be because you need to select a Lua file to open.", "Love Compiler", MessageBoxButton.OK, MessageBoxImage.Error);
}

File.Copy("Stuff/LuaDiet/lua.exe", userPath + "/lua.exe", true);
File.Copy("Stuff/LuaDiet/LuaSrcDiet.lua", userPath + "/LuaSrcDiet.lua", true);

Process luarun = new Process();
luarun.StartInfo.WorkingDirectory = @"C:\Users\Leachman";
luarun.StartInfo.FileName = "lua LuaSrcDiet.lua myscript.lua -o myscriptdone.lua";
luarun.StartInfo.UseShellExecute = false;
luarun.StartInfo.Arguments = "/all";
luarun.StartInfo.RedirectStandardOutput = true;
luarun.StartInfo.CreateNoWindow = false;
luarun.Start();

【问题讨论】:

    标签: c# process lua cmd


    【解决方案1】:

    只需编辑这些行:

    来自:

    luarun.StartInfo.FileName = "lua LuaSrcDiet.lua myscript.lua -o myscriptdone.lua";
    luarun.StartInfo.Arguments = "/all";
    

    到:

    luarun.StartInfo.FileName = "lua.exe";
    luarun.StartInfo.Arguments = "  LuaSrcDiet.lua myscript.lua -o myscriptdone.lua /all";
    

    我认为这应该可行!

    更新

    看了你的cmets后,我意识到你应该使用AsynchronousFileCopy

    来自Answer of another SO Question 的代码:

    public class AsyncFileCopier
    {
        public delegate void FileCopyDelegate(string sourceFile, string destFile);
    
        public static void AsynFileCopy(string sourceFile, string destFile)
        {
            FileCopyDelegate del = new FileCopyDelegate(FileCopy);
            IAsyncResult result = del.BeginInvoke(sourceFile, destFile, CallBackAfterFileCopied, null);
        }
    
        public static void FileCopy(string sourceFile, string destFile)
        { 
            // Code to copy the file
        }
    
        public static void CallBackAfterFileCopied(IAsyncResult result)
        {
            // Code to be run after file copy is done
        }
    }
    

    这样称呼:

    AsyncFileCopier.AsynFileCopy("Stuff/LuaDiet/lua.exe", userPath + "/lua.exe");
    

    【讨论】:

      【解决方案2】:

      看起来您正试图在文件名字段中传递参数。尝试将文件名设置为实际文件名 (lua.exe) 并将其他项目移动到参数部分。

      【讨论】:

      • 酷。谢谢。我认为这可能有效,但 CMD shell 在文件甚至复制到用户目录之前执行。我如何制作 luarun.Start();复制文件后运行?顺便感谢您的快速响应。
      • 对此无能为力.. 我认为 File.Copy 会阻塞直到它完成,所以我不确定你为什么会遇到这个问题。在设置 Process() 之前尝试检查文件是否存在
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2019-07-01
      • 1970-01-01
      • 2019-02-17
      • 2014-09-16
      相关资源
      最近更新 更多