38

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 this?

1

12 Answers 12

55

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  |"
2
  • 9
    There's one caveat, though: if the data is longer than then width specified, it will not be truncated. So you'll have to use data.Substring(0,width) on any field potentially longer than the width, which gets verbose (and repetitive/non-DRY) quick.
    – brianary
    Commented Nov 23, 2010 at 16:29
  • Just me being slow since I missed it but if the result is being displayed then the font uses needs to be fixed width also Commented Feb 1, 2013 at 17:36
28

This is a system I made for a configurable Fixed Width file writing module. It's configured with an XML file, the relevant part looking like this:

<WriteFixedWidth Table="orders" StartAt="1" Output="Return">
  <Position Start="1" Length="17" Name="Unique Identifier"/>
  <Position Start="18" Length="3" Name="Error Flag"/>
  <Position Start="21" Length="16" Name="Account Number" Justification="right"/>
  <Position Start="37" Length="8" Name="Member Number"/>
  <Position Start="45" Length="4" Name="Product"/>
  <Position Start="49" Length="3" Name="Paytype"/>
  <Position Start="52" Length="9" Name="Transit Routing Number"/>
</WriteFixedWidth>

StartAt tells the program whether your positions are 0-based or 1-based. I made that configurable because I would be copying down offsets from specs and wanted to have the config resemble the spec as much as possible, regardless of what starting index the author chose.

The Name attribute on the Position tags refer to the names of columns in a DataTable.

The following code was written for .Net 3.5, using LINQ-to-XML, so the method assumed it'd be passed an XElement with the above configuration, which you can get after you use XDocument.Load(filename) to load the XML file, then call .Descendants("WriteFixedWidth") on the XDocument object to get the configuration element.

    public void WriteFixedWidth(System.Xml.Linq.XElement CommandNode, DataTable Table, Stream outputStream)
    {
        StreamWriter Output = new StreamWriter(outputStream);
        int StartAt = CommandNode.Attribute("StartAt") != null ? int.Parse(CommandNode.Attribute("StartAt").Value) : 0;

        var positions = from c in CommandNode.Descendants(Namespaces.Integration + "Position")
                        orderby int.Parse(c.Attribute("Start").Value) ascending
                        select new
                        {
                            Name = c.Attribute("Name").Value,
                            Start = int.Parse(c.Attribute("Start").Value) - StartAt,
                            Length = int.Parse(c.Attribute("Length").Value),
                            Justification = c.Attribute("Justification") != null ? c.Attribute("Justification").Value.ToLower() : "left"
                        };

        int lineLength = positions.Last().Start + positions.Last().Length;
        foreach (DataRow row in Table.Rows)
        {
            StringBuilder line = new StringBuilder(lineLength);
            foreach (var p in positions)
                line.Insert(p.Start, 
                    p.Justification == "left" ? (row.Field<string>(p.Name) ?? "").PadRight(p.Length,' ')
                                              : (row.Field<string>(p.Name) ?? "").PadLeft(p.Length,' ') 
                    );
            Output.WriteLine(line.ToString());
        }
        Output.Flush();
    }

The engine is StringBuilder, which is faster than concatenating immutable strings together, especially if you're processing multi-megabyte files.

3
  • 4
    I just have to say this is a brilliant idea, love it! +1
    – Mohgeroth
    Commented Jan 14, 2011 at 20:59
  • I am not able to reference Namespaces.Integration, Can you please provide more details about this.
    – vikas
    Commented Jan 24, 2017 at 9:04
  • Vikas, you can find more information here, msdn.microsoft.com/en-us/library/bb353813(v=vs.110).aspx. If your XML document uses a namespace, then that is when the Namespaces.Integration is used. Commented Feb 2, 2018 at 21:50
7

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));
2

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);
    }
}
1
  • ...and the you can use standard .NET FileStream stuff to write a file of course.
    – Darren
    Commented Jun 13, 2012 at 6:51
2

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);
1

You can use a StreamWriter and in the Write(string) call use String.Format() to create a string that is the correct width for the given field.

0

Can't you use standard text file? You can read back data line by line.

1
  • Not necessarily, the text file may not be read by another C# app, but a main frame that needs a specifically formatted text file. Commented Feb 3, 2009 at 17:40
0

use String.Format()

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

0

Try using myString.PadRight(totalLengthForField, ' ')

0

You mean you want to pad all numbers on the right with spaces?

If so, String.PadRight or String.Format should get you on track.

0

You could use ASCIIEncoding.UTF8.GetBytes(text) to convert it to a byte array. Then write the byte arrays out to the file as a fixed-size record.

UTF8 varies in the number of bytes required to represent some characters, UTF16 is a little more predictable, 2 bytes per character.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.