简体   繁体   中英

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM