How can we generate a fixed length text file in C#?

T

Tarun

Hi,
I have to generate a fixed length text file.I have a file formats like
fields details as well as its length and position.what actually i have to do
that i will get the data from the databas and then i need to create a fixed
length flat file as per format.so please give me a sample for this.
 
P

Pavel Minaev

Hi,
I have to generate a fixed length text file.I have a file formats like
fields details as well as its length and  position.what actually i haveto do
that i will get the data from the databas and then i need to create a fixed
length flat file as per format.so please give me a sample for this.

Your question is extremely broad, so the answer is going to be the
same, too: use StreamWriter class and WriteLine method, and for the
latter specifically, use format strings to generate your output. For
instance, if you have one 80-char left-aligned string field followed
by one 20-char right-aligned integer field, you'd do something like
this:

string field1;
int field2;
...
using (var writer = new StreamWriter("output.txt"))
{
writer.WriteLine("{0,-80}{1,20}", field1, field2);
}

Note that using alignment (the number after comma) in format
specifiers will pad the value with required number of spaces on the
left (for positive values) or on the right (for negative values) as
needed, but it will not truncate the value if it's longer than the
alignment. So if there's a possibility that string is longer than 80
chars, or that textual representation of integer is longer than 20
chars, you'll need to handle those cases specially as per your output
format specification.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top