Search code examples
c#file-iomatrixreadfilechars

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


Maybe it's a very stupid question (I'm really noob with writing/reading/manipulate files) but I tried different method (found online and here on the site) but nothing worked :/ I have my matrix that is written in a file, and between each element of the matrix, there is a " , " like divider. I want " , " between every element but not at the end of the rows, so I opened again the file and tried to delete last char from each rows, but my code don't work!

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

Thank you!


Solution

  • How about you simply do not output the ',' if last element:

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