如何使用c#在命令提示符中执行命令

时间:2010-05-10 09:00:20

标签: c#

我想使用c#

在CMD中执行这些步骤

1 - CD C:\ MySQL \ MySQL Server 5.0 \ bin

2 - mysqldump -uroot -ppassword示例> d:\测试\ 222.sql

在手动执行此操作时,我将获得名为“222.sql”的文件

我使用下面的代码来做,但遗漏了一些事情......没有发生

public void CreateScript_AAR()
    {
        string commandLine = @"CD C:\MySQL\MySQL Server 5.0\bin\mysqldump -uroot -ppassword sample> d:\Test\222.sql""";
        System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo("cmd.exe");
        PSI.RedirectStandardInput = true;
        PSI.RedirectStandardOutput = true;
        PSI.RedirectStandardError = true;
        PSI.UseShellExecute = false;
        System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
        System.IO.StreamWriter SW = p.StandardInput;
        System.IO.StreamReader SR = p.StandardOutput;
        SW.WriteLine(commandLine);
        SW.Close();
    } 

3 个答案:

答案 0 :(得分:2)

您在1个命令中执行这两个命令,这是无效的语法。 您甚至不需要更改目录,因此只需从命令字符串中删除dirchange(CD)即可。另外,请使用像Oded这样的引语。

string commandLine = @"""C:\MySQL\MySQL Server 5.0\bin\mysqldump"" -uroot -ppassword sample > d:\Test\222.sql";

答案 1 :(得分:2)

您也可以直接从代码中调用MySqlDump.exe而不使用cmd.exe。捕获其输出并将其写入文件。以正确的编码进行编写非常重要,以便正确恢复。

    string binary = @"C:\MySQL\MySQL Server 5.0\bin\mysqldump.exe"
    string arguments = @"-uroot -ppassword sample"
    System.Diagnostics.ProcessStartInfo PSI = new    System.Diagnostics.ProcessStartInfo(binary, arguments);
    PSI.RedirectStandardInput = true;
    PSI.RedirectStandardOutput = true;
    PSI.RedirectStandardError = true;
    PSI.UseShellExecute = false;
    System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
    Encoding encoding = p.StandardOutput.CurrentEncoding;
    System.IO.StreamWriter SW = new StreamWriter(@"d:\Test\222.sql", false, encoding);
    p.WaitOnExit();
    string output = p.StandardOutput.ReadToEnd()
    SW.Write(output)
    SW.Close();

答案 2 :(得分:0)

这就是我用它来满足我的要求的方式。

public static void runResGen()
    {
        string ResGen = @"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\ResGen.exe";
        string outputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\resxMerge";
        DirectoryInfo dinfo = new DirectoryInfo(outputPath);
        DirectoryInfo latestdir = dinfo.GetDirectories().OrderByDescending(f => f.CreationTime).FirstOrDefault();
        string latestDirectory = latestdir.FullName.ToString();
        string arguments = latestDirectory + "\\StringResources.resx /str:c#,,StringResources /publicClass";
        ProcessStartInfo PSI = new ProcessStartInfo(ResGen, arguments);
        PSI.RedirectStandardInput = true;
        PSI.RedirectStandardOutput = true;
        PSI.RedirectStandardError = true;
        PSI.UseShellExecute = false;
        PSI.CreateNoWindow = true;
        System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
        Encoding encoding = p.StandardOutput.CurrentEncoding;
        p.Close();
    }