P Nam
P Nam

Reputation: 69

How to update or replace the csv data in c#

I'm new in programming, can you help me in this?, because everytime I run this it duplicates the data, now I want to replace or just update it, here is my code.. Thank you

StreamWriter writer = null;
StringBuilder strbuilder = null;
string dir = Application.StartupPath;
if (!Directory.Exists(dir))
{
    Directory.CreateDirectory(dir);
}


string path = Path.Combine(dir, "test.csv");
strbuilder = new StringBuilder();
strbuilder.Append("\n");
foreach (var a in listofuser)
{

    strbuilder.Append(a.SystemUserID.ToString() + "," + a.FullName.ToString() + "," + a.Department.ToString() +","+ Environment.NewLine);

}


writer = new StreamWriter(path, true);
writer.Write(strbuilder);
writer.Close();

Upvotes: 1

Views: 1074

Answers (1)

Tim
Tim

Reputation: 6060

When you are constructing your streamwriter, you are telling it to append (add to the end of the file). It sounds like you are wanting it to overwrite (replace the file if it already exists).

writer = new StreamWriter(path, false);

See https://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx

Upvotes: 2

Related Questions