Vb.net – Writing a fixed-width text file

vb.net

I'm writing an app that creates a fixed-width text file. What I've already written works just fine, but I'm wondering if there is a more efficient method. (By efficient, I mean executes faster, not uses less code.)

Here is the function I've created that pads or trims strings to the required length:

Private Function ToLen(ByRef strLen As String, ByRef intLen As Integer) As String

    Dim L As Integer = Len(strLen)
    If L < intLen Then
        Return strLen & Strings.Space(intLen - L)
    ElseIf L = intLen Then
        Return strLen
    Else
        Return Strings.Left(strLen, intLen)
    End If

End Function

Here is a simplified version of the code that calls it:

Using MyFile1 As New StreamWriter("C:\Temp\MyFile.txt")
    Do
        ' loop through records
        MyFile1.WriteLine(ToLen(Item1, 10) & ToLen(Item2, 50) & ToLen(Item3, 25))
    Loop
End Using

Best Answer

I would recommend using the new .NET methods for string manipulation rather than the old-style VB6 functions, for instance:

Private Function ToLen(text As String, length As Integer)
    If text.Length > length Then
        Return text.SubString(0, length)
    Else
        Return text.PadRight(length)
    End If
End Function

Then, when you are writing to the file, don't concatenate the strings together. It would be more efficient to call Write multiple times:

Using MyFile1 As New StreamWriter("C:\Temp\MyFile.txt")
    Do
        ' loop through records
        MyFile1.Write(ToLen(Item1, 10))
        MyFile1.Write(ToLen(Item2, 50))
        MyFile1.WriteLine(ToLen(Item3, 25))
    Loop
End Using
Related Topic