删除文本文件 c# 中最后一行文本上方的附加 space

removing additional space above last line text in textfile c#

我使用以下代码将数据网格视图中的条目转换为文本文件! (创建文本文件的过程成功)将数据网格视图条目转换为字符串后,我从外部附加了一个字符串(这应该出现在文本文件的最后一行)

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);
    }   
}

但是当我检查文本文件时,外部字符串(在这种情况下为"Hello")出现在最后一行但上面还有一个额外的space!我怎样才能删除这个额外的 space?

您可以使用 string.Join 连接一组字符串,中间使用分隔符。与重构一起使用 linq .Select:

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

当然你也可以在整个行集合上使用它来将它们与新行连接起来:

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

如果您更喜欢使用循环而不是 linq,那么您可以在内循环中做的是将值添加到在外循环中初始化的 List<string>。在内循环结束后对该列表的值使用 string.Join 。伪代码:

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