Creating a fixed width file in C#

后端 未结 14 2269
死守一世寂寞
死守一世寂寞 2020-12-12 17:00

What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 17:48

    You can use string.Format to easily pad a value with spaces e.g.

    string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300);
    string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300);
    
    // 'a' will be equal to "|    1|   20|  300|"
    // 'b' will be equal to "|1    |20   |300  |"
    

提交回复
热议问题