Isaiah Nelson
Isaiah Nelson

Reputation: 2490

Writing rows from a DataTable is creating a run-on write: how do I preserve each line as it is written?

Given this code:

using (StreamWriter sw = File.CreateText(file))
{
    for (int r = 0; r < originalDataTable.Rows.Count; r++)
    {
        for (int c = 0; c < originalDataTable.Columns.Count; c++)
        {
            var rowValueAtColumn = originalDataTable.Rows[r][c].ToString();

            var valueToWrite = string.Format(@"{0}{1}", rowValueAtColumn, "\t");

            if (c != originalDataTable.Columns.Count)
                sw.Write(valueToWrite);
            else 
                sw.Write(valueToWrite + @"\n");
        }
    }
}

I am trying to write a DataRow back to a file one row at a time; however, the file it is creating is creating a run-on sentence where all the data being written to the file is just in one line. There should be 590 individual lines not just one.

What do I need to add to the code above so that my lines are broken out as they are in the data table? My code just doesn't seem to be working.

Upvotes: 3

Views: 127

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

sw.Write(valueToWrite + @"\n"); is wrong. Because of the @ it is not entering a newline, you are writing the character \ then the character n.

You want to do either sw.Write(valueToWrite + "\n"); or have the program put a new line in for you by doing sw.WriteLine(valueToWrite), however that will enter Environment.NewLine which is \r\n on windows.


However you can make your code even simpler by inserting the row the separator outside of the column for loop. I also defined the two separators at the top of the loop in case you want to ever change them (What will the program you are sending this to do when you hit some data that has a \t or a \n in the text itself?), and a few other small tweaks to make the code easier to read.

string colSeperator = "\t";
string rowSeperator = "\n";

using (StreamWriter sw = File.CreateText(file))
{
    for (int r = 0; r < originalDataTable.Rows.Count; r++)
    {
        for (int c = 0; c < originalDataTable.Columns.Count; c++)
        {
            sw.Write(originalDataTable.Rows[r][c])

            sw.Write(colSeperator);
        }
        sw.Write(rowSeperator);
    }
}

Here is another similification just to show other ways to do it (now that you don't need to check originalDataTable.Columns.Count)

string colSeperator = "\t";
string rowSeperator = "\n";

using (StreamWriter sw = File.CreateText(file))
{
    foreach (DataRow row in originalDataTable.Rows)
    {
        foreach (object value in row.ItemArray))
        {
            sw.Write(value)
            sw.Write(colSeperator);
        }
        sw.Write(rowSeperator);
    }
}

Upvotes: 3

user773423
user773423

Reputation:

Change sw.Write() to sw.WriteLine()

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline.aspx

Upvotes: 2

Related Questions