如何在C#中执行cmd,然后在同一窗口中执行下面的另一个命令?

时间:2010-04-02 14:29:38

标签: c# process cmd

正是我想要完成的是一个程序,基本上只需点击一下即可设置活动分区,节省了使用cmd提示等的工作时间和技巧。

我查看了System.Management名称空间,但无法解决如何使用它:(

所以我已经使用了CMD,我有一个用C#编写的模块应用程序,基本上我想运行“DISKPART”,然后在cmd窗口中启动diskpart,然后我想要它“选择磁盘0 “接着是”select partition 1“,最后是”active“。

在CMD中这样做你自己工作正常但是应用程序被证明是尴尬的:(我设法让它做的是在一个窗口中使用Process.Start运行DiskPart,然后让它打开一个新窗口,运行下一段代码但因为新窗口没有运行diskpart cmd它不起作用> :(

有什么建议吗?

谢谢!

5 个答案:

答案 0 :(得分:3)

只要您不对输出做出决定,您就可以在C#应用中构建一个批处理文件,然后通过Process.Start(...)启动它。

您需要生成两个文件。

首先 runDiskPart.bat

diskpart /s myScript.dp

第二个 myScript.dp

...some commands...
exit

显然名称完全是任意的,但/s指令需要引用第二个文件的名称。

答案 1 :(得分:3)

经过一番搜索,我认为你可以用脚本文件做你想做的事。阅读this

因此,在使用必要的命令创建diskpart /s script.txt文件后,您可以使用Process.Start运行script.txt

答案 2 :(得分:2)

这可能有点读,所以对不起。这是我经过实践检验的方法,也许有一种更简单的方法,但这是我将代码扔在墙上,看看有什么卡住的

此问题的TLDR代码

对不起,这个实际上没有经过测试。这个理论上的作品

public static void ChangeMe()
 {

 string docPath =
  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

 string path1 = docPath + "\\Test.txt";
 string path2 = docPath + "\\Test.bat";

 string[] lines =
 {
     "select disk 0",
     "clean",
     "convert gpt",
     "create partition primary size=300",
     "format quick fs=ntfs label=Windows RE tools",
     "assign letter=T"
 };
 using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.txt")))
 {

     foreach (string line in lines)
         outputFile.WriteLine(line);
 }
 string[] lines =
 {
     "diskpart /s test.txt"
 };
 using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
 {

     foreach (string line in lines)
         outputFile.WriteLine(line);
 }
 System.Diagnostics.Process.Start(path2);
 }

如果您想做的事情可以在批处理文件中完成,那么可能过度复杂的工作是让c#编写一个.bat文件并运行它。如果需要用户输入,可以将输入放入变量中,并让C#将其写入文件中。用这种方法将需要反复试验,因为它就像用另一个木偶控制一个木偶一样。而且使用Diskpart还要复杂一些,因为您必须制作2个文件,一个是.bat文件,另一个是txt。

这只是一个批处理文件的示例,在这种情况下,该功能适用​​于Windows论坛应用程序中用于清除打印队列的按钮。

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);

    }

如果要用户输入,则可以尝试这样的操作。

这是用于将计算机IP设置为静态,但询问用户IP,网关和dns服务器是什么。

您将需要this才能正常工作

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);

    }

就像我说的那样。可能有点复杂,但是除非我写错批处理命令,否则它永远不会失败。

这是diskpart的代码。您必须了解命令提示符才能使它们起作用。使用diskpart时,您不能只编写类似

的脚本
diskpart
select disk 0
clean
convert gpt
create partition primary size=300
format quick fs=ntfs label=Windows RE tools
assign letter=T

这是因为diskpart打开了自己的窗口,其余命令只是在命令提示符窗口中引发错误 因此,您必须获取c#才能首先使用命令编写文本文件。然后使用diskpart命令创建一个批处理文件,以调用您刚编写的文本文件。

正如我最初说的,这个实际上没有经过测试。这个理论上的作品

public static void ChangeMe()
 {

 string docPath =
  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

 string path1 = docPath + "\\Test.txt";
 string path2 = docPath + "\\Test.bat";

 string[] lines =
 {
     "select disk 0",
     "clean",
     "convert gpt",
     "create partition primary size=300",
     "format quick fs=ntfs label=Windows RE tools",
     "assign letter=T"
 };
 using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.txt")))
 {

     foreach (string line in lines)
         outputFile.WriteLine(line);
 }
 string[] lines =
 {
     "diskpart /s test.txt"
 };
 using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
 {

     foreach (string line in lines)
         outputFile.WriteLine(line);
 }
 System.Diagnostics.Process.Start(path2);
 }

答案 3 :(得分:0)

如何引入延迟,例如Thread.Sleep(1000),以便其他进程有时间完成第一个命令?

答案 4 :(得分:0)

您真正想要做的是等待程序退出,然后转到下一次调用。看一下这个question