Stringbuilder to CSV

18,730

I would use StringBuilder AppendLine to create new line and than write the complete StringBuilder to the file-system with File.WriteAllText. Take a look at AppendLine

Also, WriteCSV(); will never be executed, because you have a return before.

Share:
18,730
Luca
Author by

Luca

Professional Software Engineer mainly active in dotnet and JavaScript / TypeScript.

Updated on October 06, 2022

Comments

  • Luca
    Luca over 1 year

    I have the following Problem, I'm trying to get the Content from my StringBuilder to my .csv File:

    public String GetCSV()
                {
                    System.Text.StringBuilder sb = new StringBuilder();
    
                    sb.Append(m_ID.ToString());
                    sb.Append(";");
                    sb.Append(m_Starttime.ToString());
                    sb.Append(";");
                    sb.Append(m_EndTime.ToString());
                    sb.Append(";");
                    sb.Append(m_IsSerie.ToString());
                    sb.Append(";");
                    sb.Append(m_Title);
                    sb.Append(";");
                    sb.Append(m_Description);
                    sb.Append(";");
                    sb.Append(m_Lastchange.ToString());
                    sb.Append(";");
    
                    return sb.ToString();
                    WriteCSV();
                }
    
    
            public void WriteCSV()
            {                
                string csvpath = @"c:\Temp\Kalender.csv";
    
                if (File.Exists(csvpath))
                {
                    File.Delete(csvpath);
                }
    
                    using (StreamWriter sw = File.CreateText(csvpath))
                    {
                        foreach (string CalendarItem in CalendarItem)
                        {
                            if (sb.Length > 0)
                                sb.Append(", ");
    
                            sb.Append(part);
                        }
    
                    }
    
            }
    

    Now I know how to create the CSV File already but I have no idea how I could fill it with my Content from the StringBuilder I'm sure that'll be handled by an foreach Loop right?