【问题标题】:C# pass path in argumentC# 在参数中传递路径
【发布时间】:2013-07-12 14:05:18
【问题描述】:

我在 C# 中将 cmd 作为进程启动,并且我想在参数中传递文件路径。怎么做?

Process CommandStart = new Process();
CommandStart.StartInfo.UseShellExecute = true;
CommandStart.StartInfo.RedirectStandardOutput = false;
CommandStart.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
CommandStart.StartInfo.FileName = "cmd";
CommandStart.StartInfo.Arguments = "(here i want to put a file path to a executable) -arg bla -anotherArg blabla < (and here I want to put another file path)";
CommandStart.Start();
CommandStart.WaitForExit();
CommandStart.Close();

编辑:

        Process MySQLDump = new Process();
        MySQLDump.StartInfo.UseShellExecute = true;
        MySQLDump.StartInfo.RedirectStandardOutput = false;
        MySQLDump.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        MySQLDump.StartInfo.FileName = "cmd";
        MySQLDump.StartInfo.Arguments = "/c \"\"" + MySQLDumpExecutablePath + "\" -u " + SQLActions.MySQLUser + " -p" + SQLActions.MySQLPassword + " -h " + SQLActions.MySQLServer + " --port=" + SQLActions.MySQLPort + " " + SQLActions.MySQLDatabase + " \" > " + SQLActions.MySQLDatabase + "_date_" + date + ".sql";
        MySQLDump.Start();
        MySQLDump.WaitForExit();
        MySQLDump.Close();

【问题讨论】:

  • 你想达到什么目的?
  • 执行一个可执行文件,它接受参数并返回可以存储在文件中的数据。

标签: c# visual-studio path console cmd


【解决方案1】:

您需要将文件路径放在双引号中,并使用 SLaks 提到的逐字字符串文字 (@)。

CommandStart.StartInfo.Arguments = @"""C:\MyPath\file.exe"" -arg bla -anotherArg";

OpenFileDialog 示例

using(OpenFileDialog ofd = new OpenFileDialog())
{
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
       string filePath = "\"" + ofd.FileName + "\"";

       //..set up process..

       CommandStart.StartInfo.Arguments = filePath + " -arg bla -anotherArg";
    }
 }

更新评论

您可以使用String.Format 格式化您的字符串。

string finalPath = String.Format("\"{0}{1}_date_{2}.sql\"", AppDomain.CurrentDomain.BaseDirectory, SQLActions.MySQLDatabase, date);

然后将finalPath 传递到参数中。

【讨论】:

  • 使用逐字字符串文字。
  • 我正在尝试运行 mysqldump.exe,传递 credentails 参数,然后指定导出文件。如何自动在路径中添加双斜杠,因为通过文件浏览器用户选择他的 mysqldump.exe 并且 url 不是由应用程序操作的。
  • @DavidWhite 转义(双斜杠\verbtaim 字符串文字)仅适用于您在源中键入路径时。您不需要在运行时这样做,您只需在文件路径之前和之后添加双引号(更新答案),这样如果路径中有空格,它仍然被视为一个参数。
  • @DavidWhite - 我用OpenFileDialog 示例更新了答案。它在所选文件名周围添加 ",然后将其传递给 arguments 属性。
  • 我用新代码更新了我的问题。问题是,当进程启动时,什么都没有发生,它只是冻结了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 2014-05-15
相关资源
最近更新 更多