Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello, I have an CSV File that already got multiple Columns, my goal is to add an Extra Column with new data to this Existing File.

I want to export the Excel file to a CSV, then edit it with filestream and then export it as excel

What I have tried:

<pre> using (FileStream sw = File.OpenWrite(View.path))
                {
                    var data = Encoding.Unicode.GetBytes("Preis" + "\t" + "Teil" + "\n");
                    sw.Write(data, 0, data.Length);

                    foreach (var r in View.ocEingaben)
                    {
                        data = Encoding.Unicode.GetBytes(r.Preis.ToString("F")  + "\t" + r.Teil +"\n");
                        sw.Write(data, 0, data.Length);
                    }

                }


but that didnt work, View.Path is the path of the File I selected. And in View.ocEingaben are the data which I want to add beside the last existing Column of the File, but thats not working

anyone an Idea or an tipp how I could achieve this?
Posted
Updated 7-Feb-23 1:45am
v2
Comments
Graeme_Grant 7-Feb-23 6:44am    
Load it into memory then save it back to a file with the new column.
CHill60 7-Feb-23 6:44am    
What does "not working" mean - what is actually happening?
EstKells 7-Feb-23 6:45am    
Its adding nothing after the File is still the same File
Richard MacCutchan 7-Feb-23 7:05am    
Your code is writing two fields to the file, separated by a tab charachter. So the result will be a file with two columns, although csv files generally use the comma as a separator.

1 solution

See here: That's not a database, dude![^]

CSV Files are just text: they have no "built in" sense of lines, much less columns - all of that formating information is added by the software that reads the data. All it has is a couple of values that are interpreted by software as control characters which say "this is the end of the line".

So you can't add a column directly because there is nowhere to put it! Instead, you need to read the CSV data into an application (either line-by-line or in its entirety), add the column to that data, and write the new rows back to a new file. You can then delete the original and rename the new file.

Even to insert or remove a single character in a file requires the same process: read the file data up to the insertion or deletion point while writing it to a new file, add or skip the character, then copy the rest of the file to the new file.

If you are going to start adding, modifying, or removing rows columns from your file you should really be using a database which is designed to do that.
 
Share this answer
 

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