What about EDI processing in C#?

Posted: (EET/GMT+2)

 

When was the last time you heard someone talk about EDI, or Electronic Data Interchange? Probably not recently. Yet, behind the scenes, EDI is still alive. It moves orders, invoices, and delivery notices between companies, even in 2017, often over protocols that predate the web itself.

In modern C# development, we rarely think about EDI as "text processing", but that is exactly what it is. An EDI message is a structured text file, just not more modern XML or JSON, but what is called a flat file. In EDI format, the data elements are separated by special characters such as * or ' and segments by ~ or : (colon).

Here's an example:

UNH+ME000001+ORDERS:D:96A:UN:1.1'
BGM+220+PO123456+9'
DTM+137:20170922:102'
NAD+BY+123456789::9'
NAD+SU+987654321::9'
LIN+1++12345:IN'
QTY+21:100'
PRI+AAA:12.34'
UNS+S'
CNT+2:1'
UNT+10+ME000001'

It may look old-fashioned, but it's still very efficient: fixed delimiters, predictable structure, and usually, quite small files. The good news is that with today's C# features, processing these is straightforward without any special EDI libraries (these are often commercial).

Here's a simple example that reads an EDI file and splits it into segments and elements:

string[] segments = File.ReadAllText("order.edi")
    .Split('''')
    .Where(s => !string.IsNullOrWhiteSpace(s))
    .ToArray();

foreach (string segment in segments)
{
    string[] elements = segment.Split(':');
    Console.WriteLine($"Segment: {elements[0]} ({elements.Length - 1} elements)");
}

From here, you can handle segments like BGM, DTM, LIN using simple pattern matching or dictionaries. For many integration tasks, that's enough, especially when the goal is to extract data into a database or transform it into XML or JSON for internal systems.

Of course, full EDI parsing requires understanding the specification for each document type (such as ANSI X12 or EDIFACT). There are commercial parsers available, but for lightweight needs, basic C# text parsing works surprisingly well and is very fast.

And since EDI is pure text, you can even stream it line by line for large files or use the same techniques as with NDJSON.