Home > Mobile >  Improve saving to CSV file (C#)
Improve saving to CSV file (C#)

Time:09-29

I'm writing column data to CSV file:

string sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
string csvFile = "MyName.csv";

using (StreamWriter writer = new StreamWriter(csvFile))
{
    var newLine = new StringBuilder();

    foreach (int item in someTable)
    {
        string x = (string)dt.DataTable.Rows[item].Value("abc");
        newLine.Append(x);
        newLine.Append(sep);

        string x2 = (string)dt.DataTable.Rows[item].Value("abc2");
        newLine.Append(x2);
        newLine.Append(sep);

        string x3 = (string)dt.DataTable.Rows[item].Value("abc3");
        newLine.Append(x3);
        newLine.Append(sep);

        int x4 = (int)dt.DataTable.Rows[item].Value("abc4");
        newLine.Append(x4);
        newLine.Append(sep);

        //....and more data to Append - around 20
        ...
        writer.WriteLine(newLine);
        newLine.Clear();
    }
    writer.Flush();
    writer.Close();
}

It's possible to not easier and not always repeat newLine.Append(sep); ? Or maybe other improvements?

CodePudding user response:

One potential idea would be to create a variable to represent the row such as

var row = dt.DataTable.Rows[item]; and also create a list or array to hold all of the column names, something like

string[] cols = {"abc", "abc2", "abc3"}; then inside of your current foreach loop you could do the following:

foreach (string colName in cols)
{
     newLine.Append((string)row.Value(colName));
     newLine.Append(sep);
}
writer.WriteLine(newLine);
newLine.Clear();

CodePudding user response:

You could solve this problem using StringBuilder like this:

var sb = new StringBuilder();
var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
var csvFile = "MyName.csv";

foreach (DataRow row in dt.Rows)
{
    var fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(sep, fields));
}

File.WriteAllText(csvFile , sb.ToString());
  • Related