简体   繁体   中英

How do I execute a cmd in C#, then in the same window execute another command that follows?

Right what im trying to accomplish is a program that basically sets the active partition in 1 click, saving the effort time and skill of using cmd prompt etc.

I have looked into the System.Management name space but couldn't work out how to use it :(

So i have resorted to using CMD, i have got a module application written in C# and basically i want to run "DISKPART" which then starts the diskpart in the cmd window, then i want to ask it to "Select disk 0" followed by "select partition 1" finally followed by "active".

Doing this in CMD yourself works fine but with an application its proved to be awkward :( What ive managed to get it to do is run DiskPart fine in one window with Process.Start, then get it to open a new window and run the next piece of code but because the new window hasnt ran the diskpart cmd it doesnt work >:(

Any suggestions?

Thanks!

Ash

As long as you aren't making decisions on the output, you could build a batch file in your C# app and start that via Process.Start(...) .

You'll need to generate two files.

First runDiskPart.bat :

diskpart /s myScript.dp

Second myScript.dp :

...some commands...
exit

Obviously the names are completely arbitrary but the /s directive needs to reference the name of your second file.

After some searching, I think you can do what you want with a script file. Read this .

You can therefore run diskpart /s script.txt with Process.Start after creating a script.txt file with your necessary commands.

This may be a bit of a read so im sorry in advance. And this is my tried and tested way of doing this, there may be a simpler way but this is from me throwing code at a wall and seeing what stuck

TLDR code for this question in particular

Ok sorry This one is actually not tested. this one IN THEORY works

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

If what you want to do be can be done in batch file, then the maybe over complicated work around is have c# write a .bat file and run it. If you want user input you could place the input into a variable and have c# write it into the file. it will take trial and error with this way because its like controlling a puppet with another puppet. And with Diskpart its a little more complicated because you have to make 2 files one that is a .bat and one that is a txt.

here is an example for just a batch file, In this case the function is for a push button in windows forum app that clears the print queue.

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

    }

IF you want user input then you could try something like this.

This is for setting the computer IP as static but asking the user what the IP, gateway, and dns server is.

you will need this for it to work

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

    }

Like I said. It may be a little overcomplicated but it never fails unless I write the batch commands wrong.

This is the code for diskpart. You have to understand the command prompt in order to get these to work. With diskpart you cannot just write a script like

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

This is because diskpart opens its own window and the rest of the commands just throw errors in the command prompt window so you have to get c# to first write a text file with the commands. Then a batch file with the diskpart command to call the text file that you just wrote.

As I said at first This one is actually not tested. this one IN THEORY works

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

引入一个延迟怎么样,比如Thread.Sleep(1000),让其他进程有时间完成第一个命令?

What you really want to do is wait for the program to exit and then move onto the next invocation. Take a look at this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM