有没有办法从C#应用程序中运行命令提示符命令? 若是是这样,我将如何作如下事情: shell
copy /b Image1.jpg + Archive.rar Image2.jpg
这基本上在JPG图像中嵌入了一个RAR文件。 我只是想知道是否有办法在C#中自动执行此操做。 spa
是的,有(见Matt Hamilton评论中的连接),但使用.NET的IO类会更容易也更好。 您能够使用File.ReadAllBytes来读取文件,而后使用File.WriteAllBytes来编写“嵌入式”版本。 code
这就是你要作的就是从C#运行shell命令 ip
string strCmdText; strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg"; System.Diagnostics.Process.Start("CMD.exe",strCmdText);
编辑: 字符串
这是为了隐藏cmd窗口。 get
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();
编辑:2 cmd
重要的是,参数以/C
开头,不然它将无效。 Scott Ferguson如何说:“执行字符串指定的命令,而后终止。” string
虽然从技术上讲这并无直接回答提出的问题,但它确实回答了如何作原始海报想要作的事情:组合文件。 若是有的话,这是一篇帮助新手了解Instance Hunter和Konstantin正在谈论的内容的帖子。 it
这是我用来组合文件的方法(在本例中是jpg和zip)。 请注意,我建立了一个缓冲区,其中填充了zip文件的内容(在小块中而不是在一个大的读取操做中),而后缓冲区被写入jpg文件的后面,直到zip文件的末尾是到达: io
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); } } } }
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);
试过@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());