Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 182 ยท Standard Library

Environment, Arguments and Process

Learn how C# programs talk to their surroundings: command-line args, environment variables, exit codes, console redirection, Process, Stopwatch and culture.

A program never runs in a vacuum. It is started by something (a shell, a scheduler, a container, another program) that hands it command-line arguments, environment variables and a working directory. When it finishes, it reports back with an exit code. In between, it can read from and write to the console, measure time, start other programs and format numbers according to a culture.

This lesson collects the small but essential APIs for that boundary between your code and the machine around it: args, the Environment class, exit codes, redirecting the console, the Process class, Stopwatch and a few notes on culture and globalization. These are the tools behind command-line utilities, build scripts, containers and every "works on my machine" bug. If top-level statements are new to you, read program structure first.

Command-line arguments

When you run dotnet run -- hello 42, everything after the -- arrives in your program as an array of strings. In a top-level-statement program that array is a hidden variable named args. In an explicit Main method it is the parameter. You can also call Environment.GetCommandLineArgs(), but note that its first element is the path of the program itself.

Our runner starts your program without arguments, so args is empty here. A well-written program handles that case, usually by falling back to defaults or printing usage help:

C# Handling args

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Never index args[0] without checking args.Length first; that is an IndexOutOfRangeException waiting for the first user who forgets an argument. For anything beyond two or three positional values, use a parsing library such as System.CommandLine (a NuGet package, so it is not available in our runner) instead of writing your own parser:

Terminal
# On your machine (read-only): the shell passes everything after -- to your program
dotnet run -- Ada 3
dotnet run -- "Ada Lovelace" 3     # quotes keep a space inside one argument

What the Environment class tells you

System.Environment is a static class that describes the machine, the operating system and the current process. The values below are the ones you will actually use. Some are the same everywhere, others differ per machine, which is why a real program prints them rarely and branches on them carefully.

C# Environment basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

On the sandbox (Linux, .NET 10.0.13) the program prints True for the 64-bit check, Unix as the platform, /box/submission as the current directory and /tmp/ as the temp path. On Windows you would see Win32NT, a C:\... working directory and \ as the separator. That is exactly why you should use OperatingSystem.IsWindows() and friends (or Path.Combine) instead of assuming one platform, and why you should never hard-code "\n" or "\\" in paths. See files, paths and directories.

Environment.NewLine is "\r\n" on Windows and "\n" on Linux and macOS. Console.WriteLine uses it, so you rarely need it yourself. When you write files that other systems read, decide on a newline convention explicitly instead of inheriting the current platform's.

Environment variables

Environment variables are named string settings that the operating system hands to every process. They are the classic way to configure programs without editing code: database connection strings, API keys, feature flags, and the ASPNETCORE_ENVIRONMENT value that tells a web app whether it runs in Development or Production. Containers and cloud hosts use them heavily, and the configuration lesson shows how .NET layers them over JSON files.

The key methods are GetEnvironmentVariable, SetEnvironmentVariable and GetEnvironmentVariables. Reading a missing variable returns null, not an empty string, so always handle null.

C# Reading and writing environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Four facts hide in this output:

  1. Setting a variable with SetEnvironmentVariable(name, value) changes it for the current process only (and for child processes you start afterwards). It never changes the shell that launched you.
  2. Passing null as the value deletes the variable.
  3. On Linux and macOS, names are case-sensitive: lesson_level is not found. On Windows they are not.
  4. Values are always strings. Parse them with TryParse and have a default, because users do set LESSON_LEVEL=banana.

There is also an overload with EnvironmentVariableTarget.User or .Machine that writes persistent values on Windows. It is rarely what you want, and it does nothing useful on Linux.

Environment variables are visible to every child process and, on many systems, to other users who can list processes. They are fine for configuration, but treat secrets with care: use a secret manager in production, and never print all variables to logs.

Exit codes

When a program ends, it returns a small integer to the process that started it. By convention 0 means success and any other value means failure. Shell scripts check it ($? in bash, $LASTEXITCODE in PowerShell), and CI systems fail a build when a step returns non-zero. So even a tiny tool should report errors through its exit code, not only through printed text.

There are several ways to set it in C#:

  • Return an int from Main (or return 2; in a top-level-statement program).
  • Assign Environment.ExitCode and let the program end normally.
  • Call Environment.Exit(code) to stop immediately from anywhere.
  • An unhandled exception ends the program with a non-zero code (on Linux you will see signal SIGABRT, exit code 134).
C# Setting an exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The program prints the error message to the standard error stream (the runner shows it separately from the normal output), runs the ProcessExit handler (a last chance for cleanup that runs on a normal exit and on Environment.Exit) and ends with code 5. Because the whole process stops, Environment.Exit skips finally blocks of the code that called it. Prefer returning from Main (or setting Environment.ExitCode and returning) in your own code, and keep Environment.Exit for fatal situations.

A tidy pattern is a Run method that returns the code:

C#
// Read-only sketch of a tidy entry point
return Run(args);

static int Run(string[] args)
{
    if (args.Length == 0)
    {
        Console.Error.WriteLine("usage: tool <file>");
        return 64;            // 64 = EX_USAGE in sysexits.h; any non-zero value works
    }

    try
    {
        // ... do the real work ...
        return 0;
    }
    catch (FileNotFoundException ex)
    {
        Console.Error.WriteLine(ex.Message);
        return 2;
    }
}

Redirecting the console

Console.Out, Console.Error and Console.In are ordinary TextWriter and TextReader objects, and you can replace them with Console.SetOut, SetError and SetIn. This is the standard technique for testing code that prints, and for capturing output from code you do not control. Remember to put the original writer back.

C# Capturing output with SetOut and SetIn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Console.IsOutputRedirected (and IsInputRedirected, IsErrorRedirected) tell you whether the output goes to a terminal or to a pipe or file. Programs use it to switch off colors and progress bars when somebody runs mytool > result.txt. Our runner always pipes the output, so both report True. More about reading and writing text in the input and output lessons.

The Process class

System.Diagnostics.Process represents an operating-system process: either your own (Process.GetCurrentProcess()) or another one that you start with Process.Start. It exposes memory use, thread count and start time, and for child processes it lets you send arguments and capture standard output.

C# Inspecting the current process

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Starting another program uses ProcessStartInfo. The following code is read-only: it launches git and depends on tools that exist on your machine, not on our server.

C#
// Read-only: needs git installed on YOUR machine.
using System.Diagnostics;

var startInfo = new ProcessStartInfo("git")
{
    RedirectStandardOutput = true,
    UseShellExecute = false,      // required for redirection
    CreateNoWindow = true,
};
startInfo.ArgumentList.Add("log");
startInfo.ArgumentList.Add("--oneline");
startInfo.ArgumentList.Add("-n");
startInfo.ArgumentList.Add("3");

using Process process = Process.Start(startInfo)!;
string output = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();

Console.WriteLine($"git exited with {process.ExitCode}");
Console.WriteLine(output);

Rules for launching processes safely:

  • Use ArgumentList (one entry per argument) instead of building one Arguments string. That avoids quoting bugs and command injection when part of the argument comes from a user.
  • Set UseShellExecute = false when you redirect streams, and read the output before or while waiting. If a child writes more than the pipe buffer holds and you only call WaitForExit, both sides wait for each other forever.
  • Check ExitCode after WaitForExitAsync.
  • Dispose the Process object. It holds an operating-system handle.
  • Avoid running programs at all when a library does the job: calling git from C# is fine for build tools, but parsing a PDF by launching a command-line tool is slower and harder to deploy than a library.

Measuring time with Stopwatch

DateTime.Now answers "what time is it on the wall clock?". It can jump when the user changes the clock, when daylight saving time starts or when a network time service adjusts it. To measure how long something took, use System.Diagnostics.Stopwatch, which reads a monotonic high-resolution timer that only moves forward.

C# Stopwatch versus the wall clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

We print booleans instead of the measured times because timings differ on every run and every machine. Do the same in tests: assert "took at least the sleep time", never "took exactly 80 ms". For serious performance work, a single stopwatch run is misleading (JIT warm-up, caches, noisy neighbors); use a benchmarking library such as BenchmarkDotNet (a NuGet package, read-only here). More about dates and clocks is in dates and times.

Culture and globalization

A culture (CultureInfo) bundles language and regional rules: decimal separator, date order, currency symbol, sorting. By default, ToString, Parse, string interpolation and string.Format use CultureInfo.CurrentCulture, which comes from the operating system. The same code can therefore print 1,234.5 for one user and 1.234,5 for another, and double.Parse("1,5") works in Germany but returns 15 in the United States.

Two rules prevent most bugs:

  1. Machine-readable text (files, JSON, network protocols, logs you parse later) must use CultureInfo.InvariantCulture.
  2. Text for people should use the user's culture on purpose.

Our sandbox runs in globalization-invariant mode, a setting that removes the big ICU culture database to make containers smaller. Every culture behaves like the invariant culture, so you cannot even create a German one:

C# Invariant globalization in the sandbox

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output shows 1,234,567.89, the date 03/09/2026 (month first) and Monday, 09 March 2026. On your own machine with ICU available, the following read-only snippet prints different text per culture:

C#
// Read-only: works on your machine, but throws CultureNotFoundException in the sandbox.
using System.Globalization;

double price = 1234567.891;
Console.WriteLine(price.ToString("N2", CultureInfo.GetCultureInfo("en-US")));   // 1,234,567.89
Console.WriteLine(price.ToString("N2", CultureInfo.GetCultureInfo("de-DE")));   // 1.234.567,89
Console.WriteLine(price.ToString("N2", CultureInfo.GetCultureInfo("fr-FR")));   // 1 234 567,89 (narrow no-break spaces)

If you want to turn invariant mode on or off in your own app, it is the InvariantGlobalization property in the .csproj file (see tooling). Turn it on for small Linux containers that never format localized text, and keep it off when users expect proper localized dates, currencies and sorting. More on formatting in string formatting.

Common mistakes

  • Indexing args without checking the length. Always provide defaults or usage text.
  • Forgetting that environment variables can be null. Use ?? or is null checks.
  • Assuming Windows. Hard-coded \ separators, C:\ paths and case-insensitive variable names break on Linux. Use Path.Combine and OperatingSystem.IsWindows().
  • Printing errors to the normal output. Write errors to Console.Error so that tool > out.txt still shows them on screen and scripts can separate the two streams.
  • Returning 0 after a failure. CI cannot see printed messages, only the exit code.
  • Timing with DateTime.Now. Use Stopwatch for durations.
  • Parsing numbers without a culture. Use CultureInfo.InvariantCulture for data formats.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Environment.GetEnvironmentVariable return when the variable does not exist?

    A missing variable returns null, which is different from a variable that is set to an empty string. Handle it with ?? or an is null check.
  2. 2. You call Environment.SetEnvironmentVariable("MODE", "fast") in your program. Who sees the new value?

    With the default target, the change is local to the current process (and inherited by its children). It never modifies the parent shell or other programs.
  3. 3. Which exit code conventionally means success?

    Zero means success and any non-zero value means some kind of failure. Shell scripts and CI systems rely on this convention.
  4. 4. Why should you measure durations with Stopwatch instead of subtracting DateTime.Now values?

    The wall clock can be adjusted while your code runs, producing negative or wrong durations. Stopwatch reads a monotonic high-resolution timer designed for measuring intervals.
  5. 5. When redirecting a child process's output with Process, what is the safe pattern?

    If you only wait, a child that fills the pipe buffer blocks while you also block, a deadlock. Read the stream while (or before) waiting for the process to exit, and set UseShellExecute to false so redirection works.

Summary

  • args (or the Main parameter) holds the command-line arguments as strings; check args.Length before indexing.
  • Environment describes the machine and process; use OperatingSystem.IsWindows()-style checks and Path.Combine for portability.
  • Environment variables are strings that can be null; names are case-sensitive on Linux, and changes affect only the current process and its children.
  • Report success and failure with exit codes (return from Main, Environment.ExitCode, Environment.Exit), and write errors to Console.Error.
  • Console.SetOut, SetError and SetIn redirect the console, which is great for tests; restore the original writer afterwards.
  • Process inspects or starts programs; use ArgumentList, redirect carefully and dispose it.
  • Use Stopwatch to measure durations and CultureInfo.InvariantCulture for machine-readable text; the sandbox runs in invariant globalization mode.

Next: Reflection and Attributes