Ed Mee

I am writing a Visual Basic .Net 2005 console application that extracts data from Oracle tables and I need to put out a file with fixed length fields so that a DTS in SQL Server can load the data to a SQL Server table. How can I define these fixed length fields on a fixed length record and when I run into a field that contains nulls, how can I replace with spaces I'm having a heck of a time trying to fiqure this one out and there's not much in MSDN.



Re: Visual Basic General How to write a fixed length file with fixed length fields?

BinaryCoder

You might want to try a function like the following:

Code Block

Private Shared Function PadStringToFixedLength(ByVal stringOrDBNull As Object, ByVal length As Integer) As String

Dim s As String

If length < 0 Then

Throw New ArgumentOutOfRangeException("length", length, "Length must be greater than or equal to zero.")

End If

If stringOrDBNull Is Nothing OrElse Convert.IsDBNull(stringOrDBNull) Then

s = String.Empty

Else

s = DirectCast(stringOrDBNull, String)

End If

Dim lenDiff As Integer = length - s.Length

If lenDiff < 0 Then

Throw New ArgumentException("String exceeds length.", "stringOrDBNull")

ElseIf lenDiff = 0 Then

Return stringOrDBNull

Else

Return stringOrDBNull & New String(" "c, lenDiff)

End If

End Function





Re: Visual Basic General How to write a fixed length file with fixed length fields?

Ed Mee

Thanks. This help alot.Would this work the same for numbers with some modifications





Re: Visual Basic General How to write a fixed length file with fixed length fields?

BinaryCoder

Essentially, yes. You might find the following useful, which takes any Object, including Integer, etc.

Code Block

Private Shared Function PadToFixedLength(ByVal obj As Object, ByVal length As Integer) As String

Dim s As String

If length < 0 Then

Throw New ArgumentOutOfRangeException("length", length, "Length must be greater than or equal to zero.")

End If

If obj Is Nothing OrElse Convert.IsDBNull(obj) Then

s = String.Empty

Else

s = Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture)

End If

Dim lenDiff As Integer = length - s.Length

If lenDiff < 0 Then

Throw New ArgumentException("String exceeds length.", "obj")

ElseIf lenDiff = 0 Then

Return s

Else

Return s & New String(" "c, lenDiff)

End If

End Function