Background
I am writing a .NET Core command line application as a CLI for my build system. This part of the build system includes creating a NuGet package from the class library. I use ProcessStartInfo.csand Process.csto call nuget.exeto call the pack command ( nuget.exelocation is on the system PATH).
- NOTE. I can’t use dotnet CLI for packaging because the class library is not a .NET Core project, so please don’t say, “Why don’t you just use it
dotnet pack.
Stack
- C # .NET Core (My CLI)
- C # .NET 4.5 (class library)
- Thoughtworks GoCD (Build Server)
- Windows Server 2016 (create server OS)
- Windows 10 (local machine)
, , , , CLI , ; , , , , , , - . (Me , ) - .
Cmd.cs ( )
public static class Cmd
{
public static int Execute(string filename, string arguments)
{
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = filename,
Arguments = arguments,
};
using (var process = new Process { StartInfo = startInfo })
{
try
{
process.Start();
process.WaitForExit(30000);
return process.ExitCode;
}
catch (Exception exception)
{
if (!process.HasExited)
{
process.Kill();
}
Console.WriteLine($"Cmd could not execute command {filename} {arguments}:\n{exception.Message}");
return (int)ExitCode.Exception;
}
}
}
}
Package.cs ( Cmd.cs)
var version = "1.0.0";
var package = $"MyLib.{version}";
var projectPath = "C:\Some\Made\Up\Path";
var tempPath = $"{Path.Combine(Path.GetTempPath(), "NugetPackages")}";
var packagePath = Path.Combine(tempPath, package);
if (!Directory.Exists(tempPath))
{
try
{
Directory.CreateDirectory(tempPath);
}
catch (Exception exception)
{
Console.WriteLine($"Could not create directory in user temp file: {exception.Message}");
return (int) ExitCode.FilePermission;
}
}
var filename = "nuget.exe";
var arguments = $"pack -Version {version} -OutputDirectory {tempPath} -properties Configuration=Release {projectPath}";
var exitCode = Cmd.Execute(filename, arguments);
if (exitCode != 0)
{
Console.WriteLine($"Process failed to execute and exited with exit code: {exitCode}");
return exitCode;
}
Console.WriteLine($"{package} built successfully");