简体   繁体   中英

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

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

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