I am trying to change a value of csv file in C# console. First I load the content of the csv file into the code. Then I change a value and try to save it.
This is the content of the csv before (and sadly after) execution:
1;Geg;17
2;Geg;17
3;Geg;17
During runtime the values change into: new Values
But somehow they do not get saved into the csv file.
This is my code:
main class:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
namespace csvtest
{
class Program
{
static void Main(string[] args)
{
Tabelle tab = new Tabelle();
foreach (Employees e in tab.getAll())
{
Console.WriteLine(e);
}
tab.updating(1, "fafdsdsf", 323);
}
}
}
Tabelle class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace csvtest
{
class Tabelle
{
private List<Employees>liste;
public Tabelle()
{
liste = new List<Employees>();
string[] rows = File.ReadAllLines(@"C:\Users\rbc\Desktop\csvtest\csvtest\obj\test.csv");
foreach (string row in rows)
{
string[] information = row.Split(';');
int number = int.Parse(information[0]);
string name = information[1];
double salary = double.Parse(information[2]);
liste.Add(new Employees { Number = number, Name = name, Salary = salary });
}
}
public Employees[] getAll()
{
return liste.ToArray();
}
public void adding(int number, string name, double salary)
{
liste.Add(new Employees { Number = number, Name = name, Salary = salary });
}
public void updating(int number, string name, double salary)
{
foreach (Employees e in liste)
{
if (e.Number == number)
{
e.Name = name;
e.Salary = salary;
}
}
}
~Tabelle()
{
string[] information = new string[liste.Count];
for (int i = 0; i<liste.Count; i++)
{
information[i] = liste[i].Number + ";" + liste[i].Name + ";" + liste[i].Salary;
}
File.WriteAllLines(@"C:\Users\rbc\Desktop\csvtest\csvtest\obj\test.csv", information);
}
}
}
Employees class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace csvtest
{
class Employees
{
public int Number { get; set; }
public string Name { get; set; }
public double Salary { get; set; }
public override string ToString()
{
return Number + "|" + Name + "|" + Salary;
}
}
}
I have no idea what the problem is. I appreciate any ideas or hints.
Thanks a lot in advance for your help!!
~Tabelle) except cleaning up. writing your data to a file is not cleaning up. move your code out of the finalizer - trust me, you don't need it. if you need to write exactly when you're done with the object, at least useIDisposableinstead. also: please don't roll your own CSV. there's enough libraries around that handle that stuff better than you can imagine.Save()method and call it as per your needs.