Click here to Skip to main content
15,888,590 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to Insert and/or update record in .csv file using C#. I have 3 text box that I have to insert in file (which will be inserted in 3 different columns). I referred https://stackoverflow.com/questions/14370757/editing-saving-a-row-in-a-csv-file to update in .csv file but the record is not inserting or updating at all.
I have 3 conditions to check:
1. If .csv file is empty then insert the record.
2. If record does not exist then insert new record.
3. If record exist then update record.

3 columns I want to insert is
1. ID (string)
2. Batch Number (string)
3. Location (string)

What I have tried:

String path = @"\Loc.csv";
List<String> lines = new List<String>();

if (File.Exists(path));
{
    using (StreamReader reader = new StreamReader(path))
    {
        String line;

        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains(","))
            {
                String[] split = line.Split(',');

                if (split[1].Contains(txtID.text))
                {
                    split[2] = txtBatch.text;
                    split[3] = txtLoc.text;                    
                }
            }

            lines.Add(line);
        }
    }

    using (StreamWriter writer = new StreamWriter(path, false))
    {
        foreach (String line in lines)
            writer.WriteLine(line);
    }
}


Initially file is empty. So How I can perform Insert/Update operation?
Posted
Updated 14-Mar-18 12:41pm
Comments
Member 14531967 6-Aug-19 3:10am    
can you post working cod

Create a class that encapsulates this data and manages the file. It should manage the data in memory and rewrite the file when you either call a Save method on the class, or after each operation on the data.

When you create an instance of the class, pass in the filename it's supposed to manage.

The class should then load the data from that file, if it exists. If it doesn't, don't do anything.

The class should expose methods to manipulate the data, like insert, update, delete, and managed that data in a collection of data records (another class!).

When the time comes to write the file back out, enumerate over your collection and overwrite the file that's there with the data formatted as CSV.
 
Share this answer
 
Comments
Maciej Los 14-Mar-18 17:23pm    
Short And To The Point!
webmail123 15-Mar-18 15:56pm    
@Dave. Thanks for reply. I will try to the same. :-)
First of all, please read this: Why to build your own CSV parser (or maybe not)[^]

A proper way to deal with csv data is to use:
1. classes (see solution #1 by Dave Kreskoviak[^]) then you'll be able read, write data
2. ADO.NET - OleDb

Please, see past answers:
Best way to process large amounts of CSV data?[^]
Reading and Writing CSV Files in C#[^]
How to: read from comma-delimited text files in Visual Basic | Microsoft Docs[^]
 
Share this answer
 
Comments
webmail123 15-Mar-18 15:55pm    
@Maciej. Thank you for reply. I think I will prefer ADO.Net method. I will search on the same. Btw, if you have any example of the same then can you provide it to me for referance?
Maciej Los 15-Mar-18 16:17pm    
VB.Net example is here: Read Text File Specific Columns
It's easy to change it to c#
webmail123 16-Mar-18 9:18am    
Thank you very much..
Maciej Los 16-Mar-18 9:22am    
You're very welcome.
Does my answer was helpful? If yes, then please accept my answer as a solution (green button)...
Cheers,
Maciej
webmail123 22-Mar-18 12:10pm    
I think I can not update .csv using ADO.Net method. So I am trying using different method.
There are many excel reader and writer open source dlls available like EPPLUS, NPOI.
here is example of code I have developed in one of my project, it is more focusing on reading data but you have plenty of features to write data into individual cell as well just need to explore it. little bit. The dll does not require MS office to be installed on server as it is open source.
#region Read xlsx file
                  using (ExcelPackage package = new ExcelPackage())
                  {

                      package.Load(stream);
                      if (package.Workbook.Worksheets.Count > 1 && ReaderRequestEntity.firsttimeread == true)
                      {

                          foreach (var item in package.Workbook.Worksheets)
                          {
                              ReaderRequestEntity.SheetNamesList.Add(item.Name);
                          }
                      }
                      if (package.Workbook.Worksheets.Count == 0)
                          ReaderRequestEntity.Message = "Your Excel file does not contain any work sheets";
                      else
                      {
                          ExcelWorksheet workSheet = package.Workbook.Worksheets.First();

                          int EndColumn = workSheet.Dimension.End.Column > 50 ? 50 : workSheet.Dimension.End.Column;
                          foreach (var firstRowCell in workSheet.Cells[ReaderRequestEntity.HeaderRowNo, 1, ReaderRequestEntity.HeaderRowNo, EndColumn])
                          {
                              if (ReaderRequestEntity.firsttimeread != true && (firstRowCell.Text == null || firstRowCell.Text == ""))
                                  continue;
                              else
                                  table.Columns.Add(firstRowCell.Text);
                          }
                          for (var rowNumber = ReaderRequestEntity.HeaderRowNo; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
                          {
                              if (!ReaderRequestEntity.RowsTobeIngonredList.Contains(rowNumber.ToString()))
                              {
                                  int endcolumn = (ReaderRequestEntity.firsttimeread == true ? EndColumn : table.Columns.Count);

                                  var row = workSheet.Cells[rowNumber, 1, rowNumber, endcolumn];
                                  var newRow = table.NewRow();
                                  int j = 0;
                                  foreach (var cell in row)
                                  {
                                      try
                                      {
                                          newRow[j] = cell.Text;
                                          j++;
                                      }
                                      catch (Exception ex)
                                      {
                                          if (ex.Message.Contains("Cannot find column"))
                                          {
                                              table.Columns.Add("column" + j);
                                          }
                                      }
                                  }
                                  try
                                  {
                                      table.Rows.Add(newRow);
                                  }
                                  catch (Exception)
                                  {
                                      throw;
                                  }
                              }
                          }
                      }
                  }
                  #endregion

private void formatCellValue(ref ExcelWorksheet worksheet)
{
    DataTable dtColumnMapping = (DataTable)HttpContext.Current.Session["ColumnMappingTable"];
    int i = 0;
    foreach (DataRow item in dtColumnMapping.Rows)
    {
        if (item["Dbcolumntype"].ToString() == "date")
            worksheet.Column(i).Style.Numberformat.Format = "yyyy-mm-dd";
        i++;
    }
}

public int Calculatewidth(string firstRowCell)
{
    switch (firstRowCell.Length)
    {
        case 1 - 5:
            {
                return 75;
            }
        case 6 - 9:
            {
                return 120;
            }
        default:
            return 140;
    }
}

You can get very good example for the same at dev plex.
 
Share this answer
 
Comments
Richard Deeming 15-Mar-18 14:52pm    
The question makes no mention of reading or writing Excel files.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900