Run command line code programmatically using C#

I’m using this code run in windows command prompt..
But I need this done programmatically using C# code

C:WindowsMicrosoft.NETFrameworkv4.0.30319>aspnet_regiis.exe -pdf “connection
Strings” “C:UsersXXXDesktopconnection stringDNN”

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

try this

ExecuteCommand("Your command here");

call it using process
 public void ExecuteCommand(string Command)
    {
        ProcessStartInfo ProcessInfo;
        Process Process;

        ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
        ProcessInfo.CreateNoWindow = true;
        ProcessInfo.UseShellExecute = true;

        Process = Process.Start(ProcessInfo);
    }

Method 2

You may use the Process.Start method:

Process.Start(
    @"C:WindowsMicrosoft.NETFrameworkv4.0.30319aspnet_regiis.exe",
    @"-pdf ""connection Strings"" ""C:UsersXXXDesktopconnection stringDNN"""
);

or if you want more control over the shell and be able to capture for example the standard output and error you could use the overload taking a ProcessStartInfo:
var psi = new ProcessStartInfo(@"C:WindowsMicrosoft.NETFrameworkv4.0.30319aspnet_regiis.exe")
{
    Arguments = @"-pdf ""connection Strings"" ""C:UsersXXXDesktopconnection stringDNN""",
    UseShellExecute = false,
    CreateNoWindow = true
};
Process.Start(psi);

Method 3

You should be able to do that using a process

        var proc = new Process();
        proc.StartInfo.FileName = @"C:WindowsMicrosoft.NETFrameworkv4.0.30319aspnet_regiis.exe ";
        proc.StartInfo.Arguments = string.Format(@"{0} ""{1}""" ""{2}""","-pdf","connection Strings" ,"C:UsersXXXDesktopconnection stringDNN");
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();
        string outPut = proc.StandardOutput.ReadToEnd();

        proc.WaitForExit();
        var exitCode = proc.ExitCode;
        proc.Close();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x