Kasun Karunarathna Kasun Karunarathna - 2 months ago 20
C# Question

removing additional space above last line text in textfile c#

The following code is used by me to convert the entries in a datagrid view into a text file! (The process of creating a text file is successfull) After converting the datagrid view entries into a string I append a string from outside(This should appear on the last line of the textfile)

private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string
{
StringBuilder file = new StringBuilder();
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
{
var val = dataGridView2.Rows[i].Cells[j].Value;
if (val == null)
continue;//IF NULL GO TO NEXT CELL, MAYBE YOU WANT TO PUT EMPTY SPACE
var s = val.ToString();
file.Append(s.Replace(Environment.NewLine, " "));
}

file.AppendLine(); // NEXT ROW WILL COME INTO NEXT LINE
}

file.Append("Hello");
using (StreamWriter sw = new
StreamWriter(@"C:\Users\sachinthad\Desktop\VS\Tfiles\file.txt"))
{
sw.Write(x);
}
}


But when I check text file the outside string("Hello" in this scenario) appears on the last line but there is an additional space above it! How can i remove this additional space?

Answer Source

You can use string.Joinwhich concatenates a collection of strings with a separator in between. Together with refactoring it to use linq .Select:

var lines = dataGridView2.Rows.Select(row => string.Join(" ", 
                row.Cells.Select(cell => cell.Value).Where(val => val != null));

Then of course you can also use it on the entire collection of lines to concatenate them with a new line:

// Will eliminate problem of extra \n at the end
var result = string.Join(Environment.NewLine, lines); 

If you prefer having the loops instead of linq then what you can do in the inner loop is add the values to a List<string> initialized in the outer loop. After the inner loop ends to use string.Join on the values of that list. Psudocode:

for each row:
    List<string> items = new List<string>();
    for each column in row:
        items.Add(value of column);
    file.Append(string.Join(" ", items));