Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.IO;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using System.Runtime.InteropServices;
- /**
- * CharSet defined as Ansi
- * Use CharSet.Unicode for scandinavian chars,
- * Unicode might fuck up byte sizes
- */
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
- public struct Struct1
- {
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
- public char[] voucher_type;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
- public char[] trans_type;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
- public char[] currency;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
- public char[] cur_amount;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
- public char[] amount;
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
- public char[] apar_type;
- public void Write(BinaryWriter writer, byte[] newline)
- {
- var sz = Marshal.SizeOf(this);
- IntPtr pStruct = Marshal.AllocHGlobal(sz);
- Marshal.StructureToPtr(this, pStruct, false);
- var buffer = Array.CreateInstance(typeof(byte), sz) as byte[];
- Marshal.Copy(pStruct, buffer, 0, buffer.Length);
- writer.Write(buffer);
- writer.Write(newline);
- Marshal.Release(pStruct);
- }
- public static Struct1 Read(BinaryReader reader)
- {
- var sz = Marshal.SizeOf(typeof(Struct1));
- var buffer = reader.ReadBytes(sz);
- GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
- Struct1 result = (Struct1)
- Marshal.PtrToStructure(
- handle.AddrOfPinnedObject(),
- typeof(Struct1));
- handle.Free();
- return result;
- }
- }
- class Foo {
- public static void simple(string fileName) {
- byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
- List<Struct1> expected = new List<Struct1>();
- expected.Add(new Struct1() {
- voucher_type = "0142".ToCharArray(),
- trans_type = "AR".ToCharArray(),
- currency = "NOK".ToCharArray(),
- cur_amount = "9999".ToCharArray(),
- amount = "9999".ToCharArray(),
- apar_type = "001".ToCharArray(),
- });
- expected.Add(new Struct1() {
- voucher_type = "0142".ToCharArray(),
- trans_type = "GL".ToCharArray(),
- currency = "NOK".ToCharArray(),
- cur_amount = "9999".ToCharArray(),
- amount = "9999".ToCharArray(),
- apar_type = "001".ToCharArray(),
- });
- using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
- {
- var writer = new BinaryWriter(fs);
- foreach (var item in expected)
- {
- item.Write(writer, newline);
- }
- }
- }
- static void Main(string[] args)
- {
- simple("tralala.txt");
- }
- }
- /* PRODUCES
- 0142ARNOK99999999001
- 0142GLNOK99999999001
- */
Add Comment
Please, Sign In to add comment