Paul DeVito
Paul DeVito

Reputation: 1912

How to run dotnet new command and create a new project directly in code

So I want to create new dotnet projects directly from my c# code, presumably by running a dotnet new command or something of the like, but I can’t find the syntax for it. Pretty much everything I’ve googled comes up with how to create a project via the VS GUI or the CLI, save for one discussion.

I've tried a few different iterations of something like this, with no luck. It just hangs after running the waitforexit line. Is this in the ballpark, or is there a better way?

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = @$"dotnet new foundation -n HelloApiWorld -e ""Hello"" -en ""hello"" -la ""h""",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WorkingDirectory = @"C:\testoutput"
                }
            };

            process.Start();
            process.BeginOutputReadLine();
            process.WaitForExit();

Upvotes: 1

Views: 768

Answers (1)

Manish Kumar Mall
Manish Kumar Mall

Reputation: 129

You are using cmd.exe as start process and it will not end the execution automatically. I am not sure about the template you are using for creating new project.

Please use DotNet cli directly to execute your command so that once the execution is done it will close automatically.

Try with below example to create a new project using console template.

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "dotnet",
                    Arguments = @$"new console -o myApp",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    WorkingDirectory = @"C:\testoutput"
                }
            };
        
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();

Upvotes: 3

Related Questions