运行命令提示符命令

use*_*ser 563 .net c# command-line command prompt

有没有办法从C#应用程序中运行命令提示符命令?如果是这样,我将如何做以下事情:

copy /b Image1.jpg + Archive.rar Image2.jpg
Run Code Online (Sandbox Code Playgroud)

这基本上在JPG图像中嵌入了一个RAR文件.我只是想知道是否有办法在C#中自动执行此操作.

Ram*_*Vel 866

这就是你要做的就是从C#运行shell命令

string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
Run Code Online (Sandbox Code Playgroud)

编辑:

这是为了隐藏cmd窗口.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.StartInfo = startInfo;
process.Start();
Run Code Online (Sandbox Code Playgroud)

编辑:2

重要的是,论证开始于/C否则它将无效.Scott Ferguson如何说:"执行字符串指定的命令,然后终止."

  • / C执行string指定的命令,然后终止 (158认同)
  • 仅供参考:使用process.WaitForExit()在继续之前等待进程完成并使用process.ExitCode获取进程的退出代码. (52认同)
  • 它只是告诉cmd运行和终止(不要等待任何用户输入关闭窗口) (15认同)
  • 这很棒!我可以问一下"/ C"是什么意思吗? (13认同)
  • 我不知道我是唯一一个认为这是一个可怕的想法的人.是的,这会奏效,但这完全是错的.产生CMD进程来执行简单的IO操作是错误的,即使它有效.阅读System.IO命名空间上的文档.有足够的功能可以执行您需要做的事情而不会产生不需要的进程. (8认同)
  • 谢谢你,还有一个问题.有没有办法在此期间隐藏命令提示符? (2认同)
  • 这在Windows 8中不起作用,因为命令提示符不具有提升的权限(管理权限) (2认同)
  • 您应该配置进程资源:使用(Process exeProcess = Process.Start(startInfo)){exeProcess.WaitForExit(); } (2认同)

Ogg*_*las 107

试过@RameshVel解决方案,但我无法在我的控制台应用程序中传递参数.如果有人遇到同样的问题,这是一个解决方案:

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());
Run Code Online (Sandbox Code Playgroud)

  • 这一行:cmd.StartInfo.CreateNoWindow = true; 救了我的一天. (5认同)
  • 好吧,我没有机会认为在我的机器上有一些管理员或反病毒限制,但..上面的代码工作!谢谢奥格拉斯 (2认同)
  • 有没有办法在单个 `cmd.StandardInput.WriteLine(@"cd C:\Test; pwd")` 中执行多个命令 (2认同)

Hac*_*Man 33

var proc1 = new ProcessStartInfo();
string anyCommand; 
proc1.UseShellExecute = true;

proc1.WorkingDirectory = @"C:\Windows\System32";

proc1.FileName = @"C:\Windows\System32\cmd.exe";
proc1.Verb = "runas";
proc1.Arguments = "/c "+anyCommand;
proc1.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(proc1);
Run Code Online (Sandbox Code Playgroud)

  • @Pacerier它告诉编译器转义通常必须在字符串中转义的所有字符,在本例中为\.因此,如果没有\,您的代码看起来像`proc1.FileName ="C:\\ Windows \\ System32 \\ cmd.exe";` (6认同)
  • C#中的`@`符号是什么? (2认同)
  • 应该注意`proc1.Verb = "runas";` 使这个进程以提升的权限运行......这并不总是有意的。 (2认同)

Car*_*Dev 10

虽然从技术上讲这并没有直接回答提出的问题,但它确实回答了如何做原始海报想要做的事情:组合文件.如果有的话,这是一篇帮助新手了解Instance Hunter和Konstantin正在谈论的内容的帖子.

这是我用来组合文件的方法(在本例中是jpg和zip).请注意,我创建了一个缓冲区,其中填充了zip文件的内容(在小块中而不是在一个大的读取操作中),然后缓冲区被写入jpg文件的后面,直到zip文件的末尾是到达:

private void CombineFiles(string jpgFileName, string zipFileName)
{
    using (Stream original = new FileStream(jpgFileName, FileMode.Append))
    {
        using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
        {
            var buffer = new byte[32 * 1024];

            int blockSize;
            while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
            {
                original.Write(buffer, 0, blockSize);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ela*_*lad 9

如果你想在异步模式下运行命令 - 并打印结果。你可以参加这个课程:

    public static class ExecuteCmd
{
    /// <summary>
    /// Executes a shell command synchronously.
    /// </summary>
    /// <param name="command">string command</param>
    /// <returns>string, as output of the command.</returns>
    public static void ExecuteCommandSync(object command)
    {
        try
        {
            // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            // The following commands are needed to redirect the standard output. 
            //This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput =  true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            // Get the output into a string
            string result = proc.StandardOutput.ReadToEnd();

            // Display the command output.
            Console.WriteLine(result);
        }
        catch (Exception objException)
        {
            // Log the exception
            Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
        }
    }

    /// <summary>
    /// Execute the command Asynchronously.
    /// </summary>
    /// <param name="command">string command.</param>
    public static void ExecuteCommandAsync(string command)
    {
        try
        {
            //Asynchronously start the Thread to process the Execute command request.
            Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
            //Make the thread as background thread.
            objThread.IsBackground = true;
            //Set the Priority of the thread.
            objThread.Priority = ThreadPriority.AboveNormal;
            //Start the thread.
            objThread.Start(command);
        }
        catch (ThreadStartException )
        {
            // Log the exception
        }
        catch (ThreadAbortException )
        {
            // Log the exception
        }
        catch (Exception )
        {
            // Log the exception
        }
    }

}
Run Code Online (Sandbox Code Playgroud)


Ins*_*ter 8

是的,有(参见Matt Hamilton评论中的链接),但使用.NET的IO类会更容易也更好.您可以使用File.ReadAllBytes来读取文件,然后使用File.WriteAllBytes来编写"嵌入式"版本.

  • 将整个文件加载到内存中只是为了将它们相互附加不是很有效,特别是如果文件足够大的话. (10认同)
  • 试着看看答案的精神.重点是.NET拥有足够多的IO类和函数来执行此操作,而无需调用OS shell.我提到的特定功能可能不是最好的,但那些只是最简单的.呼吁shell执行此操作完全没有任何意义. (7认同)

Mat*_*ess 8

由于某种原因,上述答案都没有帮助,似乎他们在地毯下扫除错误并且难以排除故障.所以我最终得到这样的东西,也许它会帮助别人:

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();
Run Code Online (Sandbox Code Playgroud)


Ver*_*rax 7

这也可以通过P/Invoking C 标准库的system函数来完成。

using System.Runtime.InteropServices;

[DllImport("msvcrt.dll")]
public static extern int system(string format);

system("copy Test.txt Test2.txt");
Run Code Online (Sandbox Code Playgroud)

输出:

      1 file(s) copied.
Run Code Online (Sandbox Code Playgroud)


Tyr*_*rrz 6

您可以使用CliWrap在一行中执行此操作:

var stdout = new Cli("cmd")
         .Execute("copy /b Image1.jpg + Archive.rar Image2.jpg")
         .StandardOutput;
Run Code Online (Sandbox Code Playgroud)


小智 6

如果要保持cmd窗口打开或要在winform / wpf中使用它,请像这样使用

    string strCmdText;
//For Testing
    strCmdText= "/K ipconfig";

 System.Diagnostics.Process.Start("CMD.exe",strCmdText);
Run Code Online (Sandbox Code Playgroud)

/千

将保持cmd窗口打开

  • 好的。找到了“cmd”命令及其参数的[文档](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd)。 (2认同)

kam*_*eet 5

这里有一些简单的代码版本.它也会隐藏控制台窗口 -

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();
Run Code Online (Sandbox Code Playgroud)


Sla*_*lai 5

参考 Microsoft.VisualBasic

Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);
Run Code Online (Sandbox Code Playgroud)