Fixed length strings or structures in C#

后端 未结 3 2065
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 02:32

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. I

相关标签:
3条回答
  • 2021-01-15 02:50

    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.

    0 讨论(0)
  • 2021-01-15 02:54

    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.

    0 讨论(0)
  • 2021-01-15 02:59

    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

    0 讨论(0)
提交回复
热议问题