Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

July 21, 2009

Formatting Text Files

Filed under: C#,Text Files,VB.NET @ 3:16 pm

There are often times that you need to write out text files containing data managed by your application. For example, you may need to write out a file to be read by another system. In many cases, this file needs to have a particular format, with justified or aligned columns like this:

000001  Baggins             Bilbo     20090711 
000002  Baggins             Frodo     20090701 
000003  Gamgee              Samwise   20090720 
000004  Cotton              Rosie     20090721
 

The first column is the Id, padded with 0’s. The remaining columns are the last name, first name, and date of last edit in YYYYMMDD format.

NOTE: If you can format your text file as XML instead, see this.

The StringBuilder class provides a method that makes this formatting a snap.

In C#:

using System.IO;
using System.Text;

StringBuilder sb = new StringBuilder();

foreach (Customer c in Customers.Retrieve())
{
    sb.AppendFormat("{0,-8}{1,-20}{2,-10}{3,-10:yyyyMMdd}{4}",
                    c.CustomerId.ToString().PadLeft(6, ‘0’),
                    c.LastName,
                    c.FirstName,
                    c.LastEditDate,
                    Environment.NewLine);
}

File.WriteAllText("Test.txt", sb.ToString());

In VB:

Dim sb As New System.Text.StringBuilder

For Each c As Customer In custList
    sb.AppendFormat("{0,-8}{1,-20}{2,-10}{3,-10:yyyyMMdd}{4}", _
                    c.CustomerId.ToString.PadLeft(6, "0"c), _
                    c.LastName, _
                    c.FirstName, _
                    c.LastEditDate, _
                    Environment.NewLine)
Next

My.Computer.FileSystem.WriteAllText("Test.txt", sb.ToString, False)

The code starts by creating an instance of the StringBuilder class. It then loops through each customer in the list of customers. See this for the code that creates the customer list. NOTE: A LastEditDate was added to the Customer class (not shown) in order to demonstrate date formatting.

You do not have to have business objects to use this code. You could instead loop through a DataSet, DataTable, or DataReader to get the data for your file.

The key to formatting the data into columns is the AppendFormat method of the StringBuilder. This method uses the composite formatting features of the .NET framework to build the string. In this case, the formatting parameter is a set of indexed placeholders, called format items, that look like this:

{index, length:formatString}

The index matches the formatting string with the parameter that follows. For example, index 0 is the first parameter after the format string, which is the CustomerId. Index 1 is the second parameter after the format string, which is the LastName. And so on.

The optional length defines the amount of space that is provided for the column. The system will automatically pad the field with spaces to the defined width. A positive length value will align the text to the right. A negative value aligns the text to the left.

The optional formatString defines a standard or custom format string using the .NET formatting syntax.

The format items used in this example are as follows:

  • {0, –8}: Defines that the first parameter will fill 8 characters and will be left justified. This is the CustomerId. Notice that the PadLeft method is used by the CustomerId property to pad the Id field with zeros.
  • {1, –20}: Defines that the second parameter will fill 20 characters and will be left justified. This is the last name.
  • {2,-10}: Defines that the third parameter will fill 10 characters and will be left justified. This is the first name.
  • {3,-10:yyyyMMdd}: Defines that the fourth parameter will fill 10 characters and will be left justified. The value will be formatted as a date in YYYYMMDD format. This is the last edit date.
  • {4}: Defines that the fifth parameter will be used “as is”. This is the new line constant, which is inserted to ensure each customer is on a separate line.

The final part of the code uses the ToString method of the StringBuilder to convert the StringBuilder text to a string. It then writes that string to the defined file.

To read this file back into your application as an in-memory DataTable, see this link. To read the file back in using VB’s TextFieldParser class, see this link.

Enjoy!

2 Comments

  1.   Keith Goodyear — July 24, 2009 @ 3:34 pm    Reply

    Very informative and simple program that was a big help for something I’ve needed to learn. Thank you.

  2.   harsh — December 15, 2010 @ 4:02 pm    Reply

    very helpful..thnks

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2023 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs