Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Adding CRLF to EDI Files

0.00/5 (No votes)
28 Aug 2012CPOL 10.5K  
Convert EDI file terminators to CRLF

Introduction

Adds a CRLF to EDI files replacing the ~, ... or any other line terminator.

Background

I have searched online for a solution to convert any given line terminator to CRLF; while I have found a way to do this in perl script it only worked for the ~ and not the ... terminators. So I was on a mission to find a way to do this in .NET and now have come up with an easy solution to get it done.

Using the code

The code is simple to use. Replace path with the path of the edi files to be parsed and the code will loop through each record and replace the line terminator with a CRLF.

VB code:

VB
Dim di As New DirectoryInfo(path) 'change path to your location of the edi files
Dim fiArr As FileInfo() = di.GetFiles()
Dim fri As FileInfo
For Each fri In fiArrDim vBinFile As String = path & fri.Name.Trim
    Dim fs As New FileStream(vBinFile, FileMode.Open)
    Dim b(fs.Length - 1) As Byte
    fs.Read(b, 0, b.Length - 1)
    fs.Close()
    fs = Nothing
    Dim myData As String = System.Text.ASCIIEncoding.ASCII.GetString(b)
    'Look for the line terminator and replace with crlf
    Dim str As String = myData.Trim
    Dim terminator As Char
    terminator = str.Chars(105)
    myData = myData.Replace(terminator, vbCrLf)
    Dim fw As New IO.StreamWriter(path & fri.Name.Trim.Replace(".txt", "_.txt"), False)
    fw.Write(myData)
    fw.Close()
    fw.Dispose()
Next fri

Points of Interest

I have found that if you open the file in binary mode then try replacing the terminator with 0d0a then writing back to the file in binary mode, it will truncate the beginning of each character.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)