Developers: how-to

Send ZPL to a Zebra printer from C#

A ZPL label is plain text, so sending one from C# comes down to a socket and a byte array. This page shows the whole job with nothing but the .NET base class library, and what to check when a label does not come out.

  • No packages needed
  • Tested on .NET 10
  • Updated 2026-11-14

What you send

Question What does the printer actually receive?

A ZPL format is plain text. It starts with ^XA, ends with ^XZ, and the printer prints a label when the closing command arrives. Between them, each field is a position, optionally a font, the data and a separator. Here is a small label: a line of text above a Code 128 barcode.

label.zplZPL
^XA
^FO40,30^A0N,40,40^FDBin A17^FS
^FO40,110^BY2^BCN,80,Y,N,N^FDA170042^FS
^XZ

Read it from the top. ^XA opens the format. ^FO puts the next field's upper-left corner 40 dots from the left and 30 dots down. ^A picks the scalable font 0, normal orientation, 40 by 40 dots. ^FD carries the text and ^FS closes the field. The second field sets the barcode module width with ^BY, then ^BC prints a Code 128 barcode 80 dots high with its text line. ^XZ closes the format.

Line breaks between commands are optional, so the line endings in your source file do not matter. What matters is the bytes that leave your program, and that is what the rest of this page is about.

Send it over TCP

Question How do I send a format to a network printer from C#?

Many network label printers accept raw print data on TCP port 9100. The number is a convention, so confirm it in your printer's network settings. The job is three steps: open a connection, write the bytes of the format, close the connection. This sample does not read anything back.

ZplSender.csC#
using System.Net.Sockets;
using System.Text;

public static class ZplSender
{
    // Sends one ZPL string to a printer's raw TCP port (9100 by convention).
    public static async Task SendAsync(
        string host, string zpl, int port = 9100,
        TimeSpan? timeout = null, CancellationToken ct = default)
    {
        // The printer reads bytes, so choose the encoding yourself.
        // UTF8Encoding(false) writes no byte order mark.
        byte[] payload = new UTF8Encoding(false).GetBytes(zpl);

        // One token covers connect and write: the caller's token plus a
        // deadline, so an unreachable printer cannot hang the caller.
        using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
        cts.CancelAfter(timeout ?? TimeSpan.FromSeconds(5));

        using var client = new TcpClient();
        await client.ConnectAsync(host, port, cts.Token);

        // Disposing the stream and the client closes the connection.
        await using NetworkStream stream = client.GetStream();
        await stream.WriteAsync(payload, cts.Token);
    }
}

Assumes the implicit usings of a current .NET console project. Written against the base class library only; tested on .NET 10.

Four details are worth keeping when you adapt it:

  • Bytes, not strings. The socket carries bytes, so you choose the encoding. The next section explains why that matters.
  • One deadline. A linked CancellationTokenSource gives connecting and writing a single time limit, and the caller can still cancel. Without a limit you depend on the operating system's own timeouts.
  • A token on the connect. The ConnectAsync overload that takes a CancellationToken is available from .NET 5.
  • Disposal on every path. The stream and the client are disposed even when an exception is thrown, so the connection is always closed.

Calling it looks like this. A timeout surfaces as an OperationCanceledException; a refused or unreachable connection as a SocketException.

Program.csC#
const string zpl = """
    ^XA
    ^FO40,30^A0N,40,40^FDBin A17^FS
    ^FO40,110^BY2^BCN,80,Y,N,N^FDA170042^FS
    ^XZ
    """;

try
{
    await ZplSender.SendAsync("192.168.1.50", zpl);
}
catch (OperationCanceledException)
{
    Console.WriteLine("The printer did not answer in time.");
}
catch (SocketException ex)
{
    Console.WriteLine($"Could not reach the printer: {ex.SocketErrorCode}");
}

To print several labels, write several formats, each from ^XA to ^XZ, one after the other in the same stream. The ^XZ page shows two formats sent that way.

Encoding

Question Why do the bytes matter, and which encoding do I use?

A C# string is text; a socket carries bytes. When you call GetBytes you decide which bytes stand for characters such as the ó or ñ in a Spanish address. The printer then reads those bytes with its own active character set, and ^CI selects it. The ^CI page lists every value, including the one for UTF-8, the power-up value and the firmware notes, so we do not repeat them here.

The rule that follows is short: the bytes you send and the character set the printer has been told to use must agree. If you send UTF-8, start the format with ^XA and ^CI28, on firmware that supports it. The guide recommends a ^CI at the start of every script.

Watch for a byte order mark. A StreamWriter created with Encoding.UTF8 writes the three bytes EF BB BF before your first character, while Encoding.UTF8.GetBytes does not. The guide lets a Unicode byte order mark stand in for ^CI at the start of a script, so an accidental one is not harmless. An encoding created with new UTF8Encoding(false) never writes one.

Bom.csC#
// Writes EF BB BF in front of your ^XA:
new StreamWriter(stream, Encoding.UTF8)

// Writes nothing in front of it:
new StreamWriter(stream, new UTF8Encoding(false))

A printer installed in Windows

Question How do I send ZPL to a printer that Windows knows by name?

If the printer is installed in Windows, over USB or as a queue on another machine, you can print to it by name instead of by address. Normal Windows printing hands a document to the printer driver, which converts it. A ZPL format must not be converted: it has to reach the printer exactly as written.

The Windows print spooler supports that through the data type of a print job. You open the printer by name, start a document whose data type is RAW, write your bytes and end the document. In the Win32 API the calls are OpenPrinter, StartDocPrinter (with a DOC_INFO_1 structure whose pDatatype is "RAW"), StartPagePrinter, WritePrinter, EndPagePrinter, EndDocPrinter and ClosePrinter. Microsoft documents that sequence, and a queue can report which data types it accepts.

To say it plainly: the .NET base class library has no single method that does this. System.Drawing.Printing.PrintDocument is built for drawing pages, not for sending raw bytes. In .NET you reach the spooler functions in winspool.drv through P/Invoke, which works on Windows only. We leave out a listing on purpose: it is long, and it has to be tested against your own printer and driver.

Raw means rawMicrosoft notes that for RAW data the settings inside the data take precedence over the Windows print settings, so the format has to describe everything the printer needs. If the printer also has a network address, the TCP route above is shorter and skips the driver and the spooler.

When it does not work

Question What do I check when nothing prints, or the label is wrong?

Connection refused or timed out

A SocketException with ConnectionRefused means something answered and nothing listens on that port: check the port, and whether raw printing is enabled in the printer's network settings. A timeout means nobody answered. In the sample that shows up as an OperationCanceledException from your deadline; some networks give a SocketException such as HostUnreachable instead. Check the printer's address, that your machine can reach its network, and that no firewall blocks the port.

Nothing prints, and there is no error

A successful write only means the bytes left your program. It is not a print confirmation, and this sample asks the printer nothing. Look at the printer for a paused state, media or ribbon out, or an open head. Then look at the data: a label prints when ^XZ is received, so a format without its closing command does not print.

Garbled or missing characters

Three causes cover most cases. The encoding you send and the character set chosen with ^CI disagree. A byte order mark sits in front of ^XA. Or the field data contains ^ or ~, which the printer reads as command prefixes, not text: ^FD cannot carry them directly, and the ^FD page points to ^FH for printing them.

The label prints, but shifted

Fields are placed from the label home, the upper-left corner by default. ^LH moves it, and the setting is kept until the printer is turned off or a new ^LH arrives, so one from an earlier job can shift yours. Positions are in dots, so the same ^FO values land in a different physical place on printers of different print density, and ^FO does not check that a position is on the label. The coordinates guide covers dots and density, and the first-label checklist suggests printing a configuration label to read the printer's resolution.

Test without wasting labels

Question How can I see exactly what my code sends, without printing?

Point the sender at a program on your own machine that listens on a TCP port and shows what arrives. You see the exact bytes: the ^XA at the start, the ^XZ at the end, no byte order mark and the characters you expected.

Listener.csC#
using System.Net;
using System.Net.Sockets;
using System.Text;

// Stands in for the printer: accepts one connection and shows the bytes.
var listener = new TcpListener(IPAddress.Loopback, 9100);
listener.Start();

using TcpClient client = await listener.AcceptTcpClientAsync();
using var received = new MemoryStream();
await client.GetStream().CopyToAsync(received);

Console.WriteLine(Encoding.UTF8.GetString(received.ToArray()));
Console.WriteLine($"{received.Length} bytes received");

Start the listener first, then call SendAsync("127.0.0.1", zpl); both samples use port 9100. If another program on your machine already uses that port, pick a different number and pass it as the port argument. In an automated test, compare the received bytes with the bytes you expected. That is how we checked the samples on this page: we sent a label to a local listener and compared what arrived, byte for byte, with what was sent.

This proves the transport and the encoding. It does not show how the label looks; for that you still need a printer or a renderer.

When a library pays off

Question When is a string and a socket no longer enough?

Hand-written ZPL and a socket are a fine start, and for one fixed label they may be all you need. A library starts to pay off when you meet these:

  • Templates. The same layout filled in for many different labels, and edited by someone who does not write C#.
  • Data binding. Values from orders or a database have to be escaped, since ^ and ~ cannot sit in field data, kept inside the data length the ^FD page gives, and encoded correctly.
  • Barcode rules. Each symbology has its own rules for data, check digits, quiet zones and size, and the linear barcodes guide shows how many there are. Catching a bad value before it reaches the printer is cheaper than finding out when a scanner rejects the label.
  • Queues and retries. Printers go offline, run out of media and sit behind firewalls. A real system needs a queue, retries and a record of what printed.
  • Many printers. Different resolutions change every position, and some printers speak another language.

BarcoderXBarcoderX, a .NET SDK for thermal labels, is pre-launch and its API is not final. It is designed to take that work off your hands: describe a label once, emit commands for the printer's profile, apply each barcode's rules and deliver the job over TCP, the Windows spooler or a print agent with a job queue. The Developers page shows an illustrative sample, and the Printing page describes the planned transports.

Sources ZPL facts come from our own command reference, written from Zebra's published programming guide. .NET and Windows facts come from Microsoft Learn:

Written by BarcoderX. The samples were compiled and run on .NET 10 against a local listener on 2026-11-14.

ZPL and ZPL II are trademarks of Zebra Technologies Corporation. This reference is written by BarcoderX in its own words from Zebra's published programming guide. BarcoderX is an independent product and is not affiliated with, endorsed by or sponsored by Zebra Technologies.