Run Command Prompt Commands

前端 未结 14 1947
暖寄归人
暖寄归人 2020-11-21 05:32

Is there any way to run command prompt commands from within a C# application? If so how would I do the following:

copy /b Image1.jpg + Archive.rar Image2.jp         


        
相关标签:
14条回答
  • 2020-11-21 06:15

    you can use simply write the code in a .bat format extension ,the code of the batch file :

    c:/ copy /b Image1.jpg + Archive.rar Image2.jpg

    use this c# code :

    Process.Start("file_name.bat")

    0 讨论(0)
  • 2020-11-21 06:16

    Tried @RameshVel solution but I could not pass arguments in my console application. If anyone experiences the same problem here is a solution:

    using System.Diagnostics;
    
    Process cmd = new Process();
    cmd.StartInfo.FileName = "cmd.exe";
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.CreateNoWindow = true;
    cmd.StartInfo.UseShellExecute = false;
    cmd.Start();
    
    cmd.StandardInput.WriteLine("echo Oscar");
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();
    cmd.WaitForExit();
    Console.WriteLine(cmd.StandardOutput.ReadToEnd());
    
    0 讨论(0)
  • 2020-11-21 06:16

    None of the above answers helped for some reason, it seems like they sweep errors under the rug and make troubleshooting one's command difficult. So I ended up going with something like this, maybe it will help someone else:

    var proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = @"C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE\tf.exe",
            Arguments = "checkout AndroidManifest.xml",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            WorkingDirectory = @"C:\MyAndroidApp\"
        }
    };
    
    proc.Start();
    
    0 讨论(0)
  • 2020-11-21 06:20

    with a reference to Microsoft.VisualBasic

    Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);
    
    0 讨论(0)
  • 2020-11-21 06:21

    Here is little simple and less code version. It will hide the console window too-

    System.Diagnostics.Process process = new System.Diagnostics.Process();
    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
    process.Start();
    
    0 讨论(0)
  • 2020-11-21 06:25

    You can do this using CliWrap in one line:

    var stdout = new Cli("cmd")
             .Execute("copy /b Image1.jpg + Archive.rar Image2.jpg")
             .StandardOutput;
    
    0 讨论(0)
提交回复
热议问题