0
 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.

4
  • There's no such thing as CRUD when working with text files. You can't search, you can't update, you can't* delete. Only read the entire file, append lines at the end, or rewrite the entire file. If you want to add a line anywhere else, you'll have to copy the original text. In your case, read everything in memory and then write out the headers first, then the rest of the content Commented Jun 8, 2017 at 6:39
  • No. There is. I try the code in the link above. It works. but after I adding the header, the flow of passing values are broken and its hard for me to debug how. Commented Jun 8, 2017 at 6:49
  • no there isn't. What you call CRUD has nothing to do with the real meaning of the acronym. CRUD means working on individual records. Your code rewrites the entire file. You can't update a single line because (a) you can't even find the line offset unless all records have exactly the same byte length and (b) you'll overwrite other lines, for the same reason. You can't insert anything, because you'll have to copy the rest of the file out of the way. You can only append text at the end of the file Commented Jun 8, 2017 at 6:52
  • Come on, Just try it first. Commented Jun 8, 2017 at 6:56

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

9 Comments

Added a check to exclude writing the header if the file exists
File.WriteAllText(newFileName, clientHeader); = error said: System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'E:\BR_AttendanceDownloadLogs\20170608.csv'.'
Well this is pretty clear. There is no path like E:\BR_AttendanceDownloadLogs If the drive E exists we can add a Directory.CreateDirectory(@"E:\BR_AttendanceDownloadLogs");
Or if your intent is to have a file named like E:\BR_AttendanceDownloadLogs20170608.csv then just remove the Path.Combine and uses your original code.
I mean String newFileName = "E:\\BR_AttendanceDownloadLogs" + DateTime.Today.ToString("yyyyMMdd") + ".csv"; then check for file exists or not
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.