CliWrap 3.5.0

.NET Core 3.0 .NET Standard 2.0 .NET Framework 4.6.1
dotnet add package CliWrap --version 3.5.0
NuGet\Install-Package CliWrap -Version 3.5.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CliWrap" Version="3.5.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add CliWrap --version 3.5.0
#r "nuget: CliWrap, 3.5.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install CliWrap as a Cake Addin
#addin nuget:?package=CliWrap&version=3.5.0

// Install CliWrap as a Cake Tool
#tool nuget:?package=CliWrap&version=3.5.0


Made in Ukraine Build Coverage Version Downloads Discord Donate Fuck Russia

🟒 Project status: active<sup>[?]</sup>

CliWrap is a library for interacting with external command line interfaces. It provides a convenient model for launching processes, redirecting input and output streams, awaiting completion, handling cancellation, and more.

Terms of use<sup>[?]</sup>

By using this project or its source code, for any purpose and in any shape or form, you grant your implicit agreement to all the following statements:

  • You condemn Russia and its military aggression against Ukraine
  • You recognize that Russia is an occupant that unlawfully invaded a sovereign state
  • You support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas
  • You reject false narratives perpetuated by Russian state propaganda

To learn more about the war and how you can help, click here. Glory to Ukraine! πŸ‡ΊπŸ‡¦


  • πŸ“¦ NuGet: dotnet add package CliWrap


  • Airtight abstraction over System.Diagnostics.Process
  • Fluent configuration interface
  • Flexible support for piping
  • Fully asynchronous and cancellation-aware API
  • Designed with strict immutability in mind
  • Provides safety against typical deadlock scenarios
  • Tested on Windows, Linux, and macOS
  • Targets .NET Standard 2.0+, .NET Core 3.0+, .NET Framework 4.6.1+
  • No external dependencies


Video guide

πŸ“Ί Watch Intro to CliWrap on YouTube for a deep look into the library and its features!

Intro to CliWrap

Quick overview

Similarly to a shell, CliWrap's base unit of work is a command β€” an object that encodes instructions for running a process. To build a command, start by calling Cli.Wrap(...) with the executable path, and then use the provided fluent interface to configure arguments, working directory, or other options. Once the command is configured, you can run it by calling ExecuteAsync():

using CliWrap;

var result = await Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")

// Result contains:
// -- result.ExitCode        (int)
// -- result.StartTime       (DateTimeOffset)
// -- result.ExitTime        (DateTimeOffset)
// -- result.RunTime         (TimeSpan)

The code above spawns a child process with the configured command line arguments and working directory, and then asynchronously waits for it to exit. After the task has completed, it resolves to a CommandResult object that contains the process exit code and other related information.

Warning: CliWrap will throw an exception if the underlying process returns a non-zero exit code, as it usually indicates an error. You can override this behavior by disabling result validation using WithValidation(CommandResultValidation.None).

By default, the process's standard input, output and error streams are routed to CliWrap's equivalent of the null device, which represents an empty source and a target that discards all data. You can change this by calling WithStandardInputPipe(...), WithStandardOutputPipe(...), or WithStandardErrorPipe(...) to configure pipes for the corresponding streams:

var stdOutBuffer = new StringBuilder();
var stdErrBuffer = new StringBuilder();

// ⚠ This particular example can also be simplified with ExecuteBufferedAsync().
// Continue reading below!
var result = await Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")

// Contains stdOut/stdErr buffered in-memory as string
var stdOut = stdOutBuffer.ToString();
var stdErr = stdErrBuffer.ToString();

This example command is configured to decode the data written to standard output and error streams as text, and append it to the corresponding StringBuilder buffers. After the execution is complete, these buffers can be inspected to see what the process has printed to the console.

Handling command output is a very common use case, so CliWrap offers a few high-level execution models to make these scenarios simpler. In particular, the same thing shown above can also be achieved more succinctly with the ExecuteBufferedAsync() extension method:

using CliWrap;
using CliWrap.Buffered;

// Calling `ExecuteBufferedAsync()` instead of `ExecuteAsync()`
// implicitly configures pipes that write to in-memory buffers.
var result = await Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")

// Result contains:
// -- result.StandardOutput  (string)
// -- result.StandardError   (string)
// -- result.ExitCode        (int)
// -- result.StartTime       (DateTimeOffset)
// -- result.ExitTime        (DateTimeOffset)
// -- result.RunTime         (TimeSpan)

Warning: Be mindful when using ExecuteBufferedAsync(). Programs can write arbitrary data (including binary) to output and error streams, which may be impractical to buffer in-memory. For more advanced scenarios, CliWrap also provides other piping options, which are covered in the piping section.

Command configuration

The fluent interface provided by the command object allows you to configure various options related to its execution. Below list covers all available configuration methods and their usage.

Note: Command is an immutable object β€” all configuration methods listed here create a new instance instead of modifying the existing one.


Sets the command line arguments passed to the child process.

Default: empty.


  • Set arguments from a string:
var cmd = Cli.Wrap("git")
    .WithArguments("commit -m \"my commit\"");
  • Set arguments from an array β€” each element is treated as a separate argument and spaces are escaped automatically:
var cmd = Cli.Wrap("git")
    .WithArguments(new[] {"commit", "-m", "my commit"});
var cmd = Cli.Wrap("git")
    .WithArguments(args => args

Warning: Avoid using the string overload of WithArguments(...) when the argument string is too long, contains special characters, or is formed based on variable input. For those scenarios, it's recommended to use the array or builder overloads as the more ergonomic alternatives.

Note: You can also manually instantiate ArgumentsBuilder to help with the formatting and escaping of arguments. This may be useful if you need to generate an argument string outside of the WithArguments(...) method.


Sets the working directory of the child process.

Default: current working directory, i.e. Directory.GetCurrentDirectory().


var cmd = Cli.Wrap("git")
    .WithWorkingDirectory("c:/projects/my project/");

Sets additional environment variables exposed to the child process.

Default: empty.


  • Set environment variables from a dictionary:
var cmd = Cli.Wrap("git")
    .WithEnvironmentVariables(new Dictionary<string, string?>
        ["GIT_AUTHOR_NAME"] = "John",
        ["GIT_AUTHOR_EMAIL"] = ""
  • Set environment variables using a builder:
var cmd = Cli.Wrap("git")
    .WithEnvironmentVariables(env => env
        .Set("GIT_AUTHOR_NAME", "John")
        .Set("GIT_AUTHOR_EMAIL", "")

Note: Environment variables configured using WithEnvironmentVariables(...) are applied on top of those inherited from the parent process. If you need to remove an inherited variable, set the corresponding value to null.


Sets domain, name and password of the user, under whom the child process is started.

Default: no credentials.


  • Set credentials directly:
var cmd = Cli.Wrap("git")
    .WithCredentials(new Credentials(
        domain: "some_workspace",
        userName: "johndoe",
        password: "securepassword123",
        loadUserProfile: true
  • Set credentials using a builder:
var cmd = Cli.Wrap("git")
    .WithCredentials(creds => creds

Warning: Running a process under a different username is supported across all platforms, but other options are only available on Windows.


Sets the strategy for validating the result of an execution.

Accepted values:

  • CommandResultValidation.None β€” no validation
  • CommandResultValidation.ZeroExitCode β€” ensures zero exit code when the process exits

Default: CommandResultValidation.ZeroExitCode.


  • Enable validation β€” will throw an exception if the process exits with a non-zero exit code:
var cmd = Cli.Wrap("git")
  • Disable validation:
var cmd = Cli.Wrap("git")

Sets the pipe source that will be used for the standard input stream of the process.

Default: PipeSource.Null.

Read more about this method in the piping section.


Sets the pipe target that will be used for the standard output stream of the process.

Default: PipeTarget.Null.

Read more about this method in the piping section.


Sets the pipe target that will be used for the standard error stream of the process.

Default: PipeTarget.Null.

Read more about this method in the piping section.


CliWrap provides a very powerful and flexible piping model that allows you to redirect process's streams, transform input and output data, and even chain multiple commands together with minimal effort. At its core, it's based on two abstractions: PipeSource which provides data for standard input stream, and PipeTarget which reads data coming from standard output or standard error streams.

By default, command's input pipe is set to PipeSource.Null and the output and error pipes are set to PipeTarget.Null. These objects effectively represent no-op stubs that provide empty input and discard all output respectively.

You can specify your own PipeSource and PipeTarget instances by calling the corresponding configuration methods on the command:

await using var input = File.OpenRead("input.txt");
await using var output = File.Create("output.txt");

await Cli.Wrap("foo")

Alternatively, pipes can also be configured in a slightly terser way using pipe operators:

await using var input = File.OpenRead("input.txt");
await using var output = File.Create("output.txt");

await (input | Cli.Wrap("foo") | output).ExecuteAsync();

Both PipeSource and PipeTarget have many factory methods that let you create pipe implementations for different scenarios:

  • PipeSource:
    • PipeSource.Null β€” represents an empty pipe source
    • PipeSource.FromStream(...) β€” pipes data from any readable stream
    • PipeSource.FromFile(...) β€” pipes data from a file
    • PipeSource.FromBytes(...) β€” pipes data from a byte array
    • PipeSource.FromString(...) β€” pipes from a text string
    • PipeSource.FromCommand(...) β€” pipes data from standard output of another command
  • PipeTarget:
    • PipeTarget.Null β€” represents a pipe target that discards all data
    • PipeTarget.ToStream(...) β€” pipes data into any writable stream
    • PipeTarget.ToFile(...) β€” pipes data into a file
    • PipeTarget.ToStringBuilder(...) β€” pipes data as text into StringBuilder
    • PipeTarget.ToDelegate(...) β€” pipes data as text, line-by-line, into Action<string> or Func<string, Task>
    • PipeTarget.Merge(...) β€” merges multiple outbound pipes by replicating the same data across all of them

Warning: Using PipeTarget.Null results in the corresponding stream (standard output or standard error) not being opened for the underlying process at all. In the vast majority of cases, this behavior should be functionally equivalent to piping to a null stream, but without the performance overhead of consuming and discarding unneeded data. This may be undesirable in certain situations β€” in which case it's recommended to pipe to a null stream explicitly using PipeTarget.ToStream(Stream.Null).

Below you can see some examples of what you can achieve with the help of CliWrap's piping feature:

  • Pipe a string into stdin:
var cmd = "Hello world" | Cli.Wrap("foo");
await cmd.ExecuteAsync();
  • Pipe stdout as text into a StringBuilder:
var stdOutBuffer = new StringBuilder();

var cmd = Cli.Wrap("foo") | stdOutBuffer;
await cmd.ExecuteAsync();
  • Pipe a binary HTTP stream into stdin:
using var httpClient = new HttpClient();
await using var input = await httpClient.GetStreamAsync("");

var cmd = input | Cli.Wrap("foo");
await cmd.ExecuteAsync();
  • Pipe stdout of one command into stdin of another:
var cmd = Cli.Wrap("foo") | Cli.Wrap("bar") | Cli.Wrap("baz");
await cmd.ExecuteAsync();
  • Pipe stdout and stderr into stdout and stderr of the parent process:
await using var stdOut = Console.OpenStandardOutput();
await using var stdErr = Console.OpenStandardError();

var cmd = Cli.Wrap("foo") | (stdOut, stdErr);
await cmd.ExecuteAsync();
  • Pipe stdout into a delegate:
var cmd = Cli.Wrap("foo") | Debug.WriteLine;
await cmd.ExecuteAsync();
  • Pipe stdout into a file and stderr into a StringBuilder:
var buffer = new StringBuilder();

var cmd = Cli.Wrap("foo") |
    (PipeTarget.ToFile("output.txt"), PipeTarget.ToStringBuilder(buffer));

await cmd.ExecuteAsync();
  • Pipe stdout into multiple files simultaneously:
var target = PipeTarget.Merge(

var cmd = Cli.Wrap("foo") | target;
await cmd.ExecuteAsync();
  • Pipe a string into stdin of one command, stdout of that command into stdin of another command, and then stdout and stderr of the last command into stdout and stderr of the parent process:
var cmd =
    "Hello world" |
    Cli.Wrap("foo").WithArguments("aaa") |
    Cli.Wrap("bar").WithArguments("bbb") |
    (Console.WriteLine, Console.Error.WriteLine);

await cmd.ExecuteAsync();

Execution models

CliWrap provides a few high-level execution models that offer alternative ways to reason about commands. These are essentially just extension methods that work by leveraging the piping feature shown earlier.

Buffered execution

This execution model lets you run a process while buffering its standard output and error streams in-memory. The buffered data can then be accessed after the command finishes executing.

In order to execute a command with buffering, call the ExecuteBufferedAsync() extension method:

using CliWrap;
using CliWrap.Buffered;

var result = await Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")

var exitCode = result.ExitCode;
var stdOut = result.StandardOutput;
var stdErr = result.StandardError;

By default, ExecuteBufferedAsync() assumes that the underlying process uses the default encoding (Console.OutputEncoding) for writing text to the console. To override this, specify the encoding explicitly by using one of the available overloads:

// Treat both stdout and stderr as UTF8-encoded text streams
var result = await Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")

// Treat stdout as ASCII-encoded and stderr as UTF8-encoded
var result = await Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")
    .ExecuteBufferedAsync(Encoding.ASCII, Encoding.UTF8);
Pull-based event stream

Besides executing a command as a task, CliWrap also supports an alternative model, in which the execution is represented as an event stream. This lets you start a command and react to the events it produces in real-time.

Those events are:

  • StartedCommandEvent β€” received just once, when the command starts executing (contains process ID)
  • StandardOutputCommandEvent β€” received every time the underlying process writes a new line to the output stream (contains the text as string)
  • StandardErrorCommandEvent β€” received every time the underlying process writes a new line to the error stream (contains the text as string)
  • ExitedCommandEvent β€” received just once, when the command finishes executing (contains exit code)

To execute a command as a pull-based event stream, use the ListenAsync() extension method:

using CliWrap;
using CliWrap.EventStream;

var cmd = Cli.Wrap("foo").WithArguments("bar");

await foreach (var cmdEvent in cmd.ListenAsync())
    switch (cmdEvent)
        case StartedCommandEvent started:
            _output.WriteLine($"Process started; ID: {started.ProcessId}");
        case StandardOutputCommandEvent stdOut:
            _output.WriteLine($"Out> {stdOut.Text}");
        case StandardErrorCommandEvent stdErr:
            _output.WriteLine($"Err> {stdErr.Text}");
        case ExitedCommandEvent exited:
            _output.WriteLine($"Process exited; Code: {exited.ExitCode}");

The ListenAsync() method starts the command and returns an object of type IAsyncEnumerable<CommandEvent>, which you can iterate using the await foreach construct introduced in C# 8. When using this execution model, back pressure is facilitated by locking the pipes between each iteration of the loop, preventing unnecessary buffering of data in-memory.

Note: Just like with ExecuteBufferedAsync(), you can specify custom encoding for ListenAsync() using one of its overloads.

Push-based event stream

Similarly to the pull-based stream, you can also execute a command as a push-based event stream instead:

using CliWrap;
using CliWrap.EventStream;
using System.Reactive;

await cmd.Observe().ForEachAsync(cmdEvent =>
    switch (cmdEvent)
        case StartedCommandEvent started:
            _output.WriteLine($"Process started; ID: {started.ProcessId}");
        case StandardOutputCommandEvent stdOut:
            _output.WriteLine($"Out> {stdOut.Text}");
        case StandardErrorCommandEvent stdErr:
            _output.WriteLine($"Err> {stdErr.Text}");
        case ExitedCommandEvent exited:
            _output.WriteLine($"Process exited; Code: {exited.ExitCode}");

In this case, Observe() returns a cold IObservable<CommandEvent> that represents an observable stream of command events. You can use the set of extensions provided by Rx.NET to transform, filter, throttle, or otherwise manipulate this stream.

Unlike the pull-based event stream, this execution model does not involve any back pressure, meaning that the data is pushed to the observer at the rate it becomes available.

Note: Similarly to ExecuteBufferedAsync(), you can specify custom encoding for Observe() using one of its overloads.

Combining execution models with custom pipes

The different execution models shown above are based on the piping model, but those two concepts are not mutually exclusive. When running a command using one of the built-in execution models, existing pipe configurations are preserved and extended using PipeTarget.Merge(...).

This means that you can, for example, pipe a command to a file and simultaneously execute it as an event stream:

var cmd =
    PipeSource.FromFile("input.txt") |
    Cli.Wrap("foo") |

// Iterate as an event stream and pipe to a file at the same time
// (execution models preserve configured pipes)
await foreach (var cmdEvent in cmd.ListenAsync())
    // ...

Timeout and cancellation

Command execution is asynchronous in nature as it involves a completely separate process. In many cases, it may be useful to implement an abortion mechanism to stop the execution before it finishes, either through a manual trigger or a timeout.

To do that, just pass the corresponding CancellationToken when calling ExecuteAsync():

using var cts = new CancellationTokenSource();

// Cancel automatically after a timeout of 10 seconds

var result = await Cli.Wrap("path/to/exe").ExecuteAsync(cts.Token);

In the event of a cancellation request, the underlying process will be killed and ExecuteAsync() will throw an exception of type OperationCanceledException (or its derivative, TaskCanceledException). You will need to catch this exception in your code to recover from cancellation:

    await Cli.Wrap("path/to/exe").ExecuteAsync(cts.Token);
catch (OperationCanceledException)
    // Command was cancelled

Note: Similarly to ExecuteAsync(), cancellation is also supported by ExecuteBufferedAsync(), ListenAsync(), and Observe().

Note: You can read more about CancellationToken in .NET here.

Retrieving process ID

The task returned by ExecuteAsync() and ExecuteBufferedAsync() is in fact not a regular Task<T>, but an instance of CommandTask<T>. This is a special awaitable object that contains additional information related to the currently executing command.

You can inspect the task while it's running to get the ID of the process that was started by the associated command:

var task = Cli.Wrap("path/to/exe")
    .WithArguments("--foo bar")

// Get the process ID (for example, for logging purposes)
var processId = task.ProcessId;

// Wait for the task to complete
await task;
Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard2.0 netstandard2.1
.NET Framework net461 net462 net463 net47 net471 net472 net48
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen40 tizen60
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (64)

Showing the top 5 NuGet packages that depend on CliWrap:

Package Downloads

Extension for YoutubeExplode that provides an interface to download and convert videos using FFmpeg


Pulumi Automation API, the programmatic interface for driving Pulumi programs without the CLI.


TinyFx εŸΊη‘€η»„δ»Ά


Multiple http clients


This package adds an core class library!

GitHub repositories (24)

Showing the top 5 popular GitHub repositories that depend on CliWrap:

Repository Stars
.NET Decompiler with support for PDB generation, ReadyToRun, Metadata (&more) - cross-platform!
The ultimate dirty YouTube library
B站录播姬 | BiliBili Stream Recorder | ε“”ε“©ε“”ε“©η›΄ζ’­ε½•εˆΆ
Build real-time apps (Blazor included) with less than 1% of extra code responsible for real-time updates. Host 10-1000x faster APIs relying on transparent and nearly 100% consistent caching. We call it DREAM, or Distributed REActive Memoization, and it's here to turn real-time on!
Declarative framework for building command line interfaces
Version Downloads Last updated
3.5.0 104,058 8/24/2022
3.4.4 284,198 4/24/2022
3.4.3 6,123 4/17/2022
3.4.2 194,546 3/14/2022
3.4.1 72,350 1/30/2022
3.4.0 28,226 1/7/2022
3.3.3 567,676 8/31/2021
3.3.2 654,613 4/1/2021
3.3.1 31,202 2/21/2021
3.3.0 26,453 12/29/2020
3.2.4 13,383 12/5/2020
3.2.3 101,533 11/4/2020
3.2.2 7,889 10/14/2020
3.2.1 2,372 10/13/2020
3.2.0 79,151 9/17/2020
3.1.1 32,362 9/6/2020
3.1.0 27,939 6/27/2020
3.0.3 2,212 6/22/2020
3.0.2 301,306 4/28/2020
3.0.1 622 4/26/2020
3.0.0 62,158 2/27/2020
3.0.0-alpha3 487 2/23/2020
3.0.0-alpha2 352 2/22/2020
3.0.0-alpha 387 2/21/2020
2.5.0 27,271 10/30/2019
2.4.0 45,945 10/3/2019
2.3.1 25,884 7/10/2019
2.3.0 5,515 5/28/2019
2.2.2 3,498 5/10/2019
2.2.1 4,318 4/1/2019
2.2.0 30,818 12/20/2018
2.1.0 4,156 10/14/2018
2.0.1 1,299 9/17/2018
2.0.0 1,174 9/12/2018
1.8.5 6,949 6/9/2018
1.8.4 3,260 3/9/2018
1.8.3 1,265 3/3/2018
1.8.2 1,555 2/2/2018
1.8.1 1,343 1/25/2018
1.8.0 1,274 1/25/2018
1.7.6-alpha 1,113 1/24/2018
1.7.5 1,661 1/21/2018
1.7.4 1,408 1/10/2018
1.7.3 1,383 12/19/2017
1.7.2 1,327 12/19/2017
1.7.1 1,239 12/5/2017
1.7.0 1,169 12/4/2017
1.6.1 1,493 11/25/2017
1.6.0 1,477 10/18/2017
1.5.3 1,403 10/7/2017
1.5.2 1,455 10/2/2017
1.5.1 1,507 9/8/2017
1.5.0 1,261 7/25/2017
1.4.0 1,209 7/25/2017
1.3.0 1,254 6/30/2017
1.2.3 1,266 6/1/2017
1.2.2 1,228 5/4/2017
1.2.1 1,198 4/27/2017
1.2.0 1,202 4/27/2017
1.1.0 1,177 4/26/2017
1.0.0 1,542 4/11/2017