C
C#2y ago
cyn

❔ changing values in .csv file with file i/o commands

hello, i'm trying to replace a certain column in a csv file with file i/o commands but i can't quite find out how to
10 Replies
cyn
cynOP2y ago
Here's an example of the .csv file
cyn
cynOP2y ago
...
...
string[] doctors = File.ReadAllLines("Doctor.csv");
for (int i = 1; i < doctors.Length; i++)
{
string[] doctors2 = doctors[i].Split(',');
if (doctorID == doctors2[0])
{
//Not sure what to do here to replace values
}

}
...
...
string[] doctors = File.ReadAllLines("Doctor.csv");
for (int i = 1; i < doctors.Length; i++)
{
string[] doctors2 = doctors[i].Split(',');
if (doctorID == doctors2[0])
{
//Not sure what to do here to replace values
}

}
Timtier
Timtier2y ago
You'd need to open a FileStream on this file to change the contents. Something like a StreamWriter ( or one of its implementations) would then allow you to write in it Though keep in mind that might become a bit messy considering you'll need to keep the same order of all entries to not mess with data integrity. Creating an entirely new file and removing/archiving the old one might be easier and safer unless needed
cyn
cynOP2y ago
Would that be a better option? (the creating a new file one) also is there a way to directly replace a file with another file if i do it this way?
Timtier
Timtier2y ago
Directly, maybe, not sure since im not behind a PC to google :p But basically: 1. Create new file. 2. Delete (or rename) old file 3. Rename new file to old name. 4. Delete old file if you havent yet.
cyn
cynOP2y ago
ohh okay
Timtier
Timtier2y ago
Id think its better as you can ensure the file is only replaced once your edited file is done, though it depends on your situation
cyn
cynOP2y ago
i'll try that, thank you so much <3
Timtier
Timtier2y ago
Np, good luck 😄
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?