繁体   English   中英

在Winform C#中从命令提示符执行自定义命令

[英]Executing custom commands from command prompt in winform C#

我有一个第三方可执行命令,该命令已捆绑到我的winform应用程序中。 该命令位于正在执行应用程序的目录中的一个名为“ tools”的目录内。

例如,如果我的winform mytestapp.exe放在D:\\ apps \\ mytestapp目录中,则第三方命令的路径为D:\\ apps \\ mytestapp \\ tools \\ mycommand.exe。 我正在使用Application.StartupPath来标识mytestapp.exe的位置,以便可以从任何位置运行它。

我通过启动进程System.Diagnostics.Process.Start并使用命令提示符执行该命令来执行此命令。 还有其他要传递的参数来运行命令。

我面临的问题是,如果我的应用程序和命令的路径中没有空格,则可以正常工作

例如,如果我的应用程序和命令如下放置,则可以正常运行D:\\ apps \\ mytestapp \\ mytestapp.exe D:\\ apps \\ mytestapp \\ tools \\ mycommand.exe“ parameter1”“ parameter2”-可以正常工作

但是,如果我的路径中有空白,它将失败

C:\\ Documents and settings \\ mytestapp \\ tools \\ mycommand.exe“ parameter1”“ parameter2”-不起作用C:\\ Documents and settings \\ mytestapp \\ tools \\ mycommand.exe“ parameter1 parameter2”-不起作用“ C:\\ Documents and settings \\ mytestapp \\ tools \\ mycommand.exe“” parameter1 parameter2“-不起作用” C:\\ Documents and settings \\ mytestapp \\ tools \\ mycommand.exe parameter1 parameter2“-不起作用

我尝试使用双引号执行命令,如上所示,它不起作用。 因此,如何执行我的自定义命令。 任何输入或解决此问题? 提前致谢。

这是开始过程的代码

try
        {
            System.Diagnostics.ProcessStartInfo procStartInfo =
                new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();
            proc.WaitForExit();
        }
        catch (Exception objException)
        {
            // Log the exception
        }

尝试从命令中提取工作目录,并为ProcessStartInfo对象设置WorkingDirectory属性。 然后在您的命令中仅传递文件名。

本示例假定该命令仅包含完整文件名。
需要针对您的实际命令文本进行调整

string command = "C:\Documents and settings\mytestapp\tools\mycommand.exe";
string parameters = "parameter1 parameter2";

try
{
    string workDir = Path.GetDirectoryName(command);
    string fileCmd = Path.GetFileName(command);
    System.Diagnostics.ProcessStartInfo procStartInfo =
        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + fileCmd + " " + parameters);
    procStartInfo.WorkingDirectory = workDir;
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = true;
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();
    proc.WaitForExit();
}
catch (Exception objException)
{
    // Log the exception
}

我相信以下作品:“ C:\\ Documents and settings \\ mytestapp \\ tools \\ mycommand.exe”“ parameter1”“ parameter2”

您可能还有其他问题。 尝试调试并检查是否两次使用了引号,或者中间是否有引号。

我认为这可能是因为args(和命令)字符串中需要用引号引起来,这些字符串引用包含空格的路径。 当在代码中定义非语言形式 (即在字符串前面没有@ )时,也需要转义它们,因此command字符串将按以下方式定义:

var command = "\"C:\\Documents and settings\\mytestapp\\tools\\mycommand.exe\"";
             // ^ escaped quote                                              ^ escaped quote

专门针对启动进程,我不久前编写了此方法,对于这种特定情况它可能有点过于专业化,但是可以很容易地按原样使用它,并且/或者可以使用不同的参数针对不同的设置进程编写重载:

private ProcessStartInfo CreateStartInfo(string command, string args, string workingDirectory, bool useShellExecute)
{
    var defaultWorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
    var result = new ProcessStartInfo
    {
        WorkingDirectory = string.IsNullOrEmpty(workingDirectory) 
                                 ? defaultWorkingDirectory 
                                 : workingDirectory,
        FileName = command,
        Arguments = args,
        UseShellExecute = useShellExecute,
        CreateNoWindow = true,
        ErrorDialog = false,
        WindowStyle = ProcessWindowStyle.Hidden,
        RedirectStandardOutput = !useShellExecute,
        RedirectStandardError = !useShellExecute,
        RedirectStandardInput = !useShellExecute
    };
    return result;
}

我正在像下面这样使用它; 这里的_process对象可以是任何Process -有它作为一个实例变量可能是无效的为您的使用情况; 而且OutputDataReceivedErrorDataReceived事件处理程序(未显示)仅记录输出字符串-但您可以对其进行解析,并基于该字符串采取一些措施:

public bool StartProcessAndWaitForExit(string command, string args, 
                     string workingDirectory, bool useShellExecute)
{
    var info = CreateStartInfo(command, args, workingDirectory, useShellExecute);            
    if (info.RedirectStandardOutput) _process.OutputDataReceived += _process_OutputDataReceived;
    if (info.RedirectStandardError) _process.ErrorDataReceived += _process_ErrorDataReceived;

    var logger = _logProvider.GetLogger(GetType().Name);
    try
    {
        _process.Start(info, TimeoutSeconds);
    }
    catch (Exception exception)
    {
        logger.WarnException(log.LogProcessError, exception);
        return false;
    }

    logger.Debug(log.LogProcessCompleted);
    return _process.ExitCode == 0;
}

您传递的args字符串正是您在命令行中输入它的方式,因此在您的情况下,可能类似于:

CreateStartInfo("\"C:\\Documents and settings\\mytestapp\\tools\\mycommand.exe\"", 
                "-switch1 -param1:\"SomeString\" -param2:\"Some\\Path\\foo.bar\"",
                string.Empty, true);

如果改为将路径/命令字符串放在设置文件中,则可以存储它们而无需转义引号和反斜杠。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM