Creating a fixed width file in C#

后端 未结 14 2169
死守一世寂寞
死守一世寂寞 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条回答
  • 2020-12-12 17:46

    Darren's answer to this question has inspired me to use extension methods, but instead of extending String, I extended StringBuilder. I wrote two methods:

    public static StringBuilder AppendFixed(this StringBuilder sb, int length, string value)
    {
        if (String.IsNullOrWhiteSpace(value))
            return sb.Append(String.Empty.PadLeft(length));
    
        if (value.Length <= length)
            return sb.Append(value.PadLeft(length));
        else
            return sb.Append(value.Substring(0, length));
    }
    
    public static StringBuilder AppendFixed(this StringBuilder sb, int length, string value, out string rest)
    {
        rest = String.Empty;
    
        if (String.IsNullOrWhiteSpace(value))
            return sb.AppendFixed(length, value);
    
        if (value.Length > length)
            rest = value.Substring(length);
    
        return sb.AppendFixed(length, value);
    }
    

    First one silently ignores too long string and simply cuts off the end of it, and the second one returns cut off part through out parameter of the method.

    Example:

    string rest;    
    
    StringBuilder clientRecord = new StringBuilder();
    clientRecord.AppendFixed(40, doc.ClientName, out rest); 
    clientRecord.AppendFixed(40, rest);
    clientRecord.AppendFixed(40, doc.ClientAddress, out rest);
    clientRecord.AppendFixed(40, rest);
    
    0 讨论(0)
  • 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  |"
    
    0 讨论(0)
提交回复
热议问题