C# 运行命令提示符命令
有没有办法在C应用程序中运行命令提示符命令?如果是,我将如何执行以下操作:C# 运行命令提示符命令,c#,.net,command-line,command,prompt,C#,.net,Command Line,Command,Prompt,有没有办法在C应用程序中运行命令提示符命令?如果是,我将如何执行以下操作: copy /b Image1.jpg + Archive.rar Image2.jpg 这基本上是在JPG图像中嵌入一个RAR文件。我只是想知道是否有一种方法可以在C#中自动实现这一点。是的,有(请参见Matt Hamilton评论中的链接),但是使用.NET的IO类会更简单、更好。您可以使用File.ReadAllBytes读取文件,然后使用File.WriteAllBytes写入“嵌入式”版本。这就是您所要做的所有
copy /b Image1.jpg + Archive.rar Image2.jpg
这基本上是在JPG图像中嵌入一个RAR文件。我只是想知道是否有一种方法可以在C#中自动实现这一点。是的,有(请参见Matt Hamilton评论中的链接),但是使用.NET的IO类会更简单、更好。您可以使用File.ReadAllBytes读取文件,然后使用File.WriteAllBytes写入“嵌入式”版本。这就是您所要做的所有事情,从C运行shell命令# 编辑: 这是为了隐藏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();
编辑:2
重要的是,参数以
/C
开头,否则它将不起作用。如何说:它“执行字符串指定的命令,然后终止。”虽然从技术上讲,这并没有直接回答提出的问题,但它确实回答了如何做原始海报想要做的事情:合并文件。如果有什么的话,这是一篇帮助新手理解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);
}
}
}
}
尝试了@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());
这里有一个小的简单和更少的代码版本。它也会隐藏控制台窗口-
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();
关于
由于某种原因,上述答案都没有起到作用,似乎它们掩盖了错误,使解决指挥问题变得困难。所以我最终做了这样的事情,也许它会帮助其他人:
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();
您可以在一行中完成此操作:
var result = await Cli.Wrap("cmd")
.WithArguments("copy /b Image1.jpg + Archive.rar Image2.jpg")
.ExecuteBufferedAsync();
var stdOut = result.StandardOutput;
您可以使用以下方法(如其他答案中所述)实现此目的: 当我尝试上面列出的方法时,我发现我的自定义命令无法使用上面一些答案的语法 我发现更复杂的命令需要用引号封装才能工作:
string strCmdText;
strCmdText = "'/C cd " + path + " && composer update && composer install -o'";
Process.Start("CMD.exe", strCmdText);
您只需使用
.bat
格式扩展名编写代码,批处理文件的代码:
c:/copy/b Image1.jpg+Archive.rar Image2.jpg
使用此c#代码:
Process.Start(“file_name.bat”)
如果要保持cmd窗口打开或在winform/wpf中使用它,请像这样使用它
string strCmdText;
//For Testing
strCmdText= "/K ipconfig";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
/K
如果要在异步模式下运行命令并打印结果,将保持cmd窗口打开。您可以在本课程中学习:
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
}
}
}
公共静态类ExecuteCmd
{
///
///同步执行shell命令。
///
///字符串命令
///字符串,作为命令的输出。
公共静态void ExecuteCommandSync(对象命令)
{
尝试
{
//使用“cmd”作为要运行的程序,使用“/c”作为参数,创建ProcessStartInfo。
//顺便说一下,/c告诉cmd我们希望它执行后面的命令,然后退出。
System.Diagnostics.ProcessStartInfo procStartInfo=new System.Diagnostics.ProcessStartInfo(“cmd”、“/c”+命令);
//重定向标准输出需要以下命令。
//这意味着它将被重定向到Process.StandardOutput StreamReader。
procStartInfo.RedirectStandardOutput=true;
procStartInfo.UseShellExecute=false;
//不要创建黑色窗口。
procStartInfo.CreateNoWindow=true;
//现在我们创建一个进程,分配它的ProcessStartInfo并启动它
System.Diagnostics.Process proc=新的System.Diagnostics.Process();
proc.StartInfo=procStartInfo;
proc.Start();
//将输出转换为字符串
字符串结果=proc.StandardOutput.ReadToEnd();
//显示命令输出。
控制台写入线(结果);
}
捕获(异常对象异常)
{
//记录异常
Console.WriteLine(“ExecuteCommandSync失败”+objException.Message);
}
}
///
///异步执行命令。
///
///字符串命令。
公共静态void ExecuteCommandAsync(字符串命令)
{
尝试
{
//异步启动线程以处理Execute命令请求。
线程objThread=新线程(新的参数化线程启动(ExecuteCommandSync));
//使线程成为背景线程。
objThread.IsBackground=true;
//设置线程的优先级。
objThread.Priority=ThreadPriority.overnormal;
//启动线程。
objThread.Start(命令);
}
catch(ThreadStartException)
{
//记录异常
}
捕获(线程异常)
{
//记录异常
}
捕获(例外)
{
//记录异常
}
}
}
这也可以通过C标准库的函数来完成
using System.Runtime.InteropServices;
[DllImport("msvcrt.dll")]
public static extern int system(string format);
system("copy Test.txt Test2.txt");
输出:
1 file(s) copied.
这可能是一个阅读,所以我很抱歉提前。这是我尝试和测试过的方法,可能有一个更简单的方法,但这是从我扔代码到墙上,看看什么卡住了 如果可以用批处理文件完成,那么可能过于复杂的解决方法是让c#编写一个.bat文件并运行它。如果需要用户输入,可以将输入放入变量中,并让c#将其写入文件。这种方法需要反复试验,因为它就像用另一个木偶控制一个木偶 下面是一个示例,在这种情况下,函数用于推送,但
string strCmdText;
//For Testing
strCmdText= "/K ipconfig";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
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
}
}
}
using System.Runtime.InteropServices;
[DllImport("msvcrt.dll")]
public static extern int system(string format);
system("copy Test.txt Test2.txt");
1 file(s) copied.
using System.IO;
using System;
public static void ClearPrintQueue()
{
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"@echo off",
"net stop spooler",
"del %systemroot%\\System32\\spool\\Printers\\* /Q",
"net start spooler",
//this deletes the file
"del \"%~f0\"" //do not put a comma on the last line
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
public static void SetIPStatic()
{
//These open pop up boxes which ask for user input
string STATIC = Microsoft.VisualBasic.Interaction.InputBox("Whats the static IP?", "", "", 100, 100);
string SUBNET = Microsoft.VisualBasic.Interaction.InputBox("Whats the Subnet?(Press enter for default)", "255.255.255.0", "", 100, 100);
string DEFAULTGATEWAY = Microsoft.VisualBasic.Interaction.InputBox("Whats the Default gateway?", "", "", 100, 100);
string DNS = Microsoft.VisualBasic.Interaction.InputBox("Whats the DNS server IP?(Input required, 8.8.4.4 has already been set as secondary)", "", "", 100, 100);
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"SETLOCAL EnableDelayedExpansion",
"SET adapterName=",
"FOR /F \"tokens=* delims=:\" %%a IN ('IPCONFIG ^| FIND /I \"ETHERNET ADAPTER\"') DO (",
"SET adapterName=%%a",
"REM Removes \"Ethernet adapter\" from the front of the adapter name",
"SET adapterName=!adapterName:~17!",
"REM Removes the colon from the end of the adapter name",
"SET adapterName=!adapterName:~0,-1!",
//the variables that were set before are used here
"netsh interface ipv4 set address name=\"!adapterName!\" static " + STATIC + " " + STATIC + " " + DEFAULTGATEWAY,
"netsh interface ipv4 set dns name=\"!adapterName!\" static " + DNS + " primary",
"netsh interface ipv4 add dns name=\"!adapterName!\" 8.8.4.4 index=2",
")",
"ipconfig /flushdns",
"ipconfig /registerdns",
":EOF",
"DEL \"%~f0\"",
""
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
var processResults = await ProcessEx.RunAsync("git.exe", "pull");
//get process result
foreach (var output in processResults.StandardOutput)
{
Console.WriteLine("Output line: " + output);
}