首页 > 解决方案 > 如何运行 dotnet new 命令并直接在代码中创建新项目

问题描述

所以我想直接从我的 c# 代码创建新的 dotnet 项目,大概是通过运行dotnet new命令或类似的东西,但我找不到它的语法。我在谷歌上搜索到的几乎所有内容都提出了如何通过 VS GUI 或 CLI 创建项目,仅用于一次讨论。

我已经尝试了类似这样的一些不同的迭代,但没有运气。它只是在运行 waitforexit 行后挂起。这是在球场上,还是有更好的方法?

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

标签: c#templates.net-coredotnet-cli

解决方案


您正在使用 cmd.exe 作为启动进程,它不会自动结束执行。我不确定您用于创建新项目的模板。

请直接使用 DotNet cli 执行您的命令,以便执行完成后它会自动关闭。

尝试使用以下示例使用控制台模板创建一个新项目。

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

推荐阅读