Need to write many customer records to a single line in text file

1.1k views Asked by At

I have a client that wants a text file with all the text on a single line. Like an EDI file has.

I have a datatable with thousands of customers and customer information. My method loops through the datatable grabs the customer info and writes it to a text file. Each line in the text file has information for one customer. There are thousands of customers, which means thousands of lines in the text file.

I don't know how to put all the customers on one single line in the text file. If anybody has some suggestions I would appreciate it.

4

There are 4 answers

0
Reed Copsey On

Instead of using WriteLine to write each customer, you can use Write (which won't add the new line), and also Write some delimiter (space, tab, etc) between each customer.

0
evanmcdonnal On

Say I have some array of strings ( string[] ) with all the names, it could really be any collection implementing IEnumerable<T> just do;

 string OneBigLine = String.Join(MyDelimiter, myStringArray);
 File.WriteAllText(OneBigLine);

Or to make it all one line;

File.WriteAllText(String.Join(MyDelimiter, myStringArray));
0
Pierre-Luc Pineault On

If you already have the file opened, you can append more customers with your StreamWriter Write method, instead of the classic WriteLine.

using (StreamWriter sw = new StreamWriter("file.txt"))
{
    foreach (Customer customer in customers)
    {
        sw.Write(customer.Name);
    }    
}

If you need to open the file each time, you can use the overload of StreamWriter that appends new text instead of overwriting it.

using (StreamWriter sw = new StreamWriter("file.txt", true))
{
    sw.Write(customer.Name);  
}

You will also need to add a delimiter manually if you need one.

1
J.R. On

Thanks everyone for your answers. However, I went with the following. The writeline has a default return carriage line feed characters like this. \r\n

I adjusted the Newline property to a blank string like this sw.NewLine = "";.

sw is my streamwriter. This does exactly what I wanted. Instead of adding new rows, it just creates one very long row.