写入文件时如何防止输出最后一个逗号字符

How to prevent the output of last comma character in line when writting to file

也许这是一个非常愚蠢的问题(我对 writing/reading/manipulate 文件真的很菜鸟)但我尝试了不同的方法(在网上和网站上找到)但没有任何效果:/ 我有一个写在文件中的矩阵,在矩阵的每个元素之间,有一个像分隔符一样的“,”。 我想在每个元素之间但不在行末尾使用“,”,所以我再次打开文件并尝试从每一行中删除最后一个字符,但我的代码不起作用!

//writing on the file
         using (TextWriter tw = new StreamWriter("PATH"))
         {
             for (int i = 0; i < colonne; i++)
             {
                 for (int y = 0; y < righe; y++)
                 {
                     tw.Write(matrice[y, i]+","); 
                 }
                 tw.WriteLine();
             }
         }

         using (FileStream fs = File.OpenWrite("PATH"))
         {
             fs.SetLength(fs.Length - 1);
             fs.Close();
         }

谢谢!

如果最后一个元素:

你干脆不输出 ',' 怎么样?
for (int i = 0; i < colonne; i++)
{
    for (int y = 0; y < righe; y++)
    {
        tw.Write(matrice[y, i]); 

        if (y < righe - 1)
            tw.Write(",");
    }

    tw.WriteLine();
}