tags:

views:

2860

answers:

3

I need to create a structure or series of strings that are fixed lenght for a project I am working on. Currently it is written in COBOL and is a communication application. It sends a fixed length record via the web and recieves a fixed length record back. I would like to write it as a structure for simplicity, but so far the best thing I have found is a method that uses string.padright to put the string terminator in the correct place.

I could write a class that encapsulates this and returns a fixed length string, but I'm hoping to find a simple way to fill a structure and use it as a fixed length record.

edit--

The fixed length record is used as a parameter in a URL, so its http:\somewebsite.com\parseme?record="firstname lastname address city state zip". I'm pretty sure I won't have to worry about ascii to unicode conversions since it's in a url. It's a little larger than that and more information is passed than address, about 30 or 35 fields.

+4  A: 

Add the MarshalAs tag to your structure. Here is an example:

<StructLayout (LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Public Structure OSVERSIONINFO
    Public dwOSVersionInfoSize As Integer
    Public dwMajorVersion As Integer
    Public dwMinorVersion As Integer
    Public dwBuildNumber As Integer
    Public dwPlatformId As Integer

    <MarshalAs (UnmanagedType.ByValTStr, SizeConst:=128)> _
    Public szCSDVersion As String
End Structure

http://bytes.com/groups/net-vb/369711-defined-fixed-length-string-structure

Jonathan Allen
MarshalAs is used to interop with PInvoke (unmanaged code). Since it seems the OP is staying in managed code until making the request to the web, it would never be marshalled.
Mark Brackett
A: 

You could use the VB6 compat FixedLengthString class, but it's pretty trivial to write your own.

If you need parsing and validation and all that fun stuff, you may want to take a look at FileHelpers which uses attributes to annotate and parse fixed length records.

FWIW, on anything relatively trivial (data processing, for instance) I'd probably just use a ToFixedLength() extension method that took care of padding or truncating as needed when writing out the records. For anything more complicated (like validation or parsing), I'd turn to FileHelpers.

Mark Brackett
A: 

As an answer, you should be able to use char arrays of the correct size, without having to marshal.

Also, the difference between a class and a struct in .net is minimal. A struct cannot be null while a class can. Otherwise their use and capabilities are pretty much identical.

Finally, it sounds like you should be mindful of the size of the characters that are being sent. I'm assuming (I know, I know) that COBOL uses 8bit ASCII characters, while .net strings are going to use a UTF-16 encoded character set. This means that a 10 character string in COBOL is 10 bytes, but in .net, the same string is 20 bytes.

Paul Whitehurst