Sam
Sam

Reputation: 15

Adding a header to a CSV file program using C#

 InitializeComponent();

 conDB = new csvfile();
 conDB.Path = "E:\\BR_AttendanceDownloadLogs" + 
 DateTime.Today.ToString("yyyyMMdd") + ".csv";

 fillCombo();

As beginner of programming and a very first time doing CRUD to a csv file in c#. I refer to this link:https://social.msdn.microsoft.com/Forums/en-US/27a98772-2dc6-4197-9f75-6cc119d4a88a/how-to-edit-a-line-from-a-text-file-using-c?forum=Vsexpressvcs that I've been located my source and useful to my program. But it was not satisfy to my specific satisfaction. I want to add header from it. Yes, I successfully added a header using this code.

   String newFileName = "E:\\BR_AttendanceDownloadLogs" +
   DateTime.Today.ToString("yyyyMMdd") + ".csv";

        string clientHeader = "\"EmployeeCode\"" + ",\"" + "Date" + "\",\""+
        "Time" + "\",\"" + "Type" + "\",\"" + "Remarks" + "\"" +
        Environment.NewLine;

        File.WriteAllText(newFileName, clientHeader);

        conDB.InsertEntrie(txtidno.Text, DatePicker.Text, TimePicker.Text, 
        cmbtype.Text, txtremarks.Text);
            //txtID.Text = Convert.ToString(conDB.Entries()-1);
            txtvalue = Convert.ToString(conDB.Entries() - 1);

        fillCombo();
        txtidno.Text = "";
        DatePicker.Text = "";
        TimePicker.Text = "";
        cmbtype.Text = "";
        txtremarks.Text = "";

But after successfully added my header like this: "EmployeeCode","Date","Time","Type","Remarks" The flow of codes are infected by this type of field in the header. Note! I change the format just like what my header form. The rest of my function that reading the line in csv file is affected by my header.It return to undesirable error. Hope that anyone can rescue me to my Island of error.

Upvotes: 0

Views: 10520

Answers (2)

Sam
Sam

Reputation: 15

I solved this problem credit with the help of Steve. First of all I add this code to the form.

  InitializeComponent();
  conDB = new csvfile();
  conDB.Path = "E:\\BR_AttendanceDownloadLogs" + 
  DateTime.Today.ToString("yyyyMMdd") + ".csv";

  String newFileName = "E:\\BR_AttendanceDownloadLogs" + 
  DateTime.Today.ToString("yyyyMMdd") + ".csv";

  if (!File.Exists(newFileName))
  {
    string clientHeader = "\"EmployeeCode\"" + ",\"" + "Date" + "\",\"" +
    "Time" + "\",\"" + "Type" + "\",\"" + "Remarks" + "\"" +
    Environment.NewLine;
    File.WriteAllText(newFileName, clientHeader);
  }
  fillCombo();

Then to my other class I add this function to add entry from the user input. Thanks to steve.

  public bool InsertEntrie(string idnumber, string date, string time, string 
  type, string remarks)
    {            
        CreateConfigFile();
        try
        {
           string line = $"\"{idnumber}\",\"{date}\",\"{time}\",\"
            {type}\",\"{remarks}\"{Environment.NewLine}";
            File.AppendAllText(data_path, line);                
            return true;
        }
        catch (Exception ee)
        {
            string temp = ee.Message;
            return false;
        }
    }

Then I have this code to my form in button click event.

    private void button1_Click(object sender, EventArgs e)
    {          
       conDB.InsertEntrie(txtidno.Text, DatePicker.Text, TimePicker.Text, 
       cmbtype.Text, txtremarks.Text);
       txtvalue = Convert.ToString(conDB.Entries() - 1);
    }

Upvotes: 0

Steve
Steve

Reputation: 216243

You can substitute all that StreamWriter code with a more concise File.AppendAllText and replace your string concatenations with an interpolated string.
These changes will result in a more clean InsertEntry method

public bool InsertEntry(string idnumber, string date, string time, string type, string remarks)
{
    try
    {
        string line = $"\"{idnumber}\",\"{date}\",\"{time}\",\"{type}\",\"{remarks}\"{Environment.NewLine}";
        File.AppendAllText(data_path, line);
        return true;
    }
    catch (Exception ee)
    {
        string temp = ee.Message;
        return false;
    }
}

Of course, the button1 click should write the header just one time, not everytime it is clicked. To avoid this from happening you need to check if the file exists or not before writing the header.

String newFileName = @"E:\BR_AttendanceDownloadLogs" + 
                     DateTime.Today.ToString("yyyyMMdd") + ".csv");
if(!File.Exists(newFileName))
{
    string clientHeader = $"\"EmployeeCode\",\"Date\",\"Time\",\"Type\",\"Remarks\"{Environment.NewLine}";
    File.WriteAllText(newFileName, clientHeader);
}

Upvotes: 1

Related Questions