code_junkie

Creating a fixed width file in C#

Nov 10th, 2011
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300);
  2. string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300);
  3.  
  4. // 'a' will be equal to "| 1| 20| 300|"
  5. // 'b' will be equal to "|1 |20 |300 |"
  6.  
  7. <WriteFixedWidth Table="orders" StartAt="1" Output="Return">
  8. <Position Start="1" Length="17" Name="Unique Identifier"/>
  9. <Position Start="18" Length="3" Name="Error Flag"/>
  10. <Position Start="21" Length="16" Name="Account Number" Justification="right"/>
  11. <Position Start="37" Length="8" Name="Member Number"/>
  12. <Position Start="45" Length="4" Name="Product"/>
  13. <Position Start="49" Length="3" Name="Paytype"/>
  14. <Position Start="52" Length="9" Name="Transit Routing Number"/>
  15. </WriteFixedWidth>
  16.  
  17. public void WriteFixedWidth(System.Xml.Linq.XElement CommandNode, DataTable Table, Stream outputStream)
  18. {
  19. StreamWriter Output = new StreamWriter(outputStream);
  20. int StartAt = CommandNode.Attribute("StartAt") != null ? int.Parse(CommandNode.Attribute("StartAt").Value) : 0;
  21.  
  22. var positions = from c in CommandNode.Descendants(Namespaces.Integration + "Position")
  23. orderby int.Parse(c.Attribute("Start").Value) ascending
  24. select new
  25. {
  26. Name = c.Attribute("Name").Value,
  27. Start = int.Parse(c.Attribute("Start").Value) - StartAt,
  28. Length = int.Parse(c.Attribute("Length").Value),
  29. Justification = c.Attribute("Justification") != null ? c.Attribute("Justification").Value.ToLower() : "left"
  30. };
  31.  
  32. int lineLength = positions.Last().Start + positions.Last().Length;
  33. foreach (DataRow row in Table.Rows)
  34. {
  35. StringBuilder line = new StringBuilder(lineLength);
  36. foreach (var p in positions)
  37. line.Insert(p.Start,
  38. p.Justification == "left" ? (row.Field<string>(p.Name) ?? "").PadRight(p.Length,' ')
  39. : (row.Field<string>(p.Name) ?? "").PadLeft(p.Length,' ')
  40. );
  41. Output.WriteLine(line.ToString());
  42. }
  43. Output.Flush();
  44. }
  45.  
  46. handle.WriteLine(s20.PadRight(20));
  47. handle.WriteLine(s80.PadRight(80));
  48. handle.WriteLine(s10.PadRight(10));
  49. handle.WriteLine(s2.PadRight(2));
Add Comment
Please, Sign In to add comment