Search code examples
c#csvheaderstreamwriter

C#, windows form, StremWriter, Header line


I am trying to add a header in my running csv file log. This is what I want,

Project Name, Project SN, Project Build < first Row that will never change, unless file was deleted. In that case create a new header line.

After that row, I want the data to be added to next line every time.

Here is what I have so far.

// Write to CSV string path = if (!File.Exists(path)) { File.CreateText(path);

        }

        string projectName = ProjectName_TextBox.Text;
        string projetcBuild = ProjectBuild_TextBox.Text;
        string projectSN = SN_TextBox.Text;
        string header = "Project Name, Project Build, Project SN\n";

        
        using (StreamWriter sw = new StreamWriter(path, true)) // true for appending data to file, false to overwrite in file
        {
           
            sw.WriteLine(header);
            
           
            sw.WriteLine(string.Format(projectName + "," + projetcBuild.ToString() + "," + projectSN.ToString()));
            
            
        }

What this does is it adds the header and data each time a button is clicked. I want the header added to the file only once. Only the data from form will get appended to next line which I think I have. Please help.


Solution

  • File.CreateText returns you a streamwriter; you can use it and also take the opportunity to write the header

    
    string header = "Project Name, Project Build, Project SN\n";
    
    // Write to CSV string path
    try{
      StreamWriter sw;
    
      if (!File.Exists(path)) {
        sw = File.CreateText(path);
        sw.WriteLine(header);
      } else
        sw = File.AppendText(path);
    
      string projectName = ProjectName_TextBox.Text;
      string projetcBuild = ProjectBuild_TextBox.Text;
      string projectSN = SN_TextBox.Text;
     
      sw.WriteLine(projectName + "," + projetcBuild + "," + projectSN);
                
    }
    finally{
      sw.Dispose(); 
    }
    
    

    You don't need to call ToString on a string. You don't need to call format on a string with no placeholders. You shouldn't really bother writing your own csv writer; there are so many good libraries out there that does it. This simple implementation will fall down as soon as someone puts a comma in one of the textboxes