Reputation: 43
I have an CSV file with 10 lines. In every line some data: Id, Data, number, etc. I wanna replace some line base on Id column. Could you take a look please and tell how I can fix it. Thanks. my code is:
public static IEnumerable<Invoice> Replace(int Id, string invoice)
{
var replacedLine = "";
var lines = File.ReadAllLines("Invoices.csv");
var listInvoices = new List<Invoice>();
foreach (var line in lines)
{
var value = line.Split(";");
if(Int32.Parse(value[1]) == Id) //value[1] it's Id column
{
replacedLine = line.Replace(line, invoice);
}
if(replacedLine != "")
value = replacedLine.Split(";");
var invoice1 = new Invoice()
{
DateAndTimeCreation = value[0],
Id = Int32.Parse(value[1]),
Status = GetStatus(value[2]),
Amount = Decimal.Parse(value[3]),
PaymentMethod = GetPayment(value[4])
};
listInvoices.Add(invoice1);
}
File.WriteAllText("Invoices.csv", replacedLine);
return listInvoices;
}
At this moment problem is - it removing all lines and add replaced line(I got file with 1 line). Also i tried apply:
File.Replace("Invoices.csv", "Invoices.csv", replacedLine);
Anyone could help replacing line without loosing else lines? thanks
Upvotes: 0
Views: 1053
Reputation: 2818
Approach the task by splitting it into logical parts:
So:
// setting up stuff
var path = "Invoices.csv";
var id = 1;
var regex = new Regex("^[^;]+;" + id); // regex magic
var replacement = "foo bar"; // add value here
// doing the work
var originalLines = File.ReadAllLines(path);
var replacedLines = originalLines.Select(x => regex.IsMatch(x) ? replacement : x);
File.WriteAllLines(path, replacedLines);
It should be noted that this will only work with your particular CSV. In general, the format is much more tricky. For example, just splitting by ;
is dangerous because there can be strings containing the semicolon as an escaped value. If you need any serious processing of CSV data, I suggest you use a specialized parser like CsvHelper.
UPDATE: using a regular expression instead of StartsWith
due to the format of the input data.
Going into details about regular expressions is out of scope for this question, so I will just explain what this one does:
^
= start of string[^;]
= anything except a semicolon+
= the previous statement (in brackets) can be repeated 1 or more timesid
- the literal value of the ID to search forRegular expressions are tightly bound to the particular data you expect them to work on, so this will probably require modifications if you would want to apply it to a different CSV.
Upvotes: 1