Creating a fixed width file in C#

后端 未结 14 2168
死守一世寂寞
死守一世寂寞 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:29

    The various padding/formatting posts prior will work sufficiently enough, but you may be interested in implementing ISerializable.

    Here's an msdn article about Object Serialization in .NET

    0 讨论(0)
  • 2020-12-12 17:31

    Try FileHelpers: www.filehelpers.com

    Here's an example: http://www.filehelpers.com/quick_start_fixed.html

    0 讨论(0)
  • 2020-12-12 17:34

    You can use http://www.filehelpers.com/

    0 讨论(0)
  • 2020-12-12 17:34

    use String.Format()

    http://msdn.microsoft.com/en-us/library/aa331875.aspx

    0 讨论(0)
  • 2020-12-12 17:35

    Use the .PadRight function (for left aligned data) of the String class. So:

    handle.WriteLine(s20.PadRight(20));
    handle.WriteLine(s80.PadRight(80));
    handle.WriteLine(s10.PadRight(10));
    handle.WriteLine(s2.PadRight(2));
    
    0 讨论(0)
  • 2020-12-12 17:36

    I am using an extension method on string, yes the XML commenting may seem OTT for this, but if you want other devs to re-use...

    public static class StringExtensions
    {
    
        /// <summary>
        /// FixedWidth string extension method.  Trims spaces, then pads right.
        /// </summary>
        /// <param name="self">extension method target</param>
        /// <param name="totalLength">The length of the string to return (including 'spaceOnRight')</param>
        /// <param name="spaceOnRight">The number of spaces required to the right of the content.</param>
        /// <returns>a new string</returns>
        /// <example>
        /// This example calls the extension method 3 times to construct a string with 3 fixed width fields of 20 characters, 
        /// 2 of which are reserved for empty spacing on the right side.
        /// <code>
        ///const int colWidth = 20;
        ///const int spaceRight = 2;
        ///string headerLine = string.Format(
        ///    "{0}{1}{2}",
        ///    "Title".FixedWidth(colWidth, spaceRight),
        ///    "Quantity".FixedWidth(colWidth, spaceRight),
        ///    "Total".FixedWidth(colWidth, spaceRight));
        /// </code>
        /// </example>
        public static string FixedWidth(this string self, int totalLength, int spaceOnRight)
        {
            if (totalLength < spaceOnRight) spaceOnRight = 1; // handle silly use.
    
            string s = self.Trim();
    
            if (s.Length > (totalLength - spaceOnRight))
            {
                s = s.Substring(0, totalLength - spaceOnRight);
            }
    
            return s.PadRight(totalLength);
        }
    }
    
    0 讨论(0)
提交回复
热议问题