1

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();
4
  • If the file is reasonably small (and a CSV file really should be) then I suppose a simple approach would be to read the contents of the file into an in-memory collection (List<T> of some custom object), edit whatever you want to edit in that collection, and then write the whole thing back out to a new file (overwriting the original if you want). Commented Feb 17, 2017 at 16:42
  • The question is very broad. How much data do you want to update or replace? Where are the instructions to update/change coming from? Commented Feb 17, 2017 at 16:45
  • I have bulk of files in there Sir, so I need to replace or update it everytime I will run the program Commented Feb 17, 2017 at 16:47
  • It's like when I run the program it will create a csv file, then when I re run it it will replace or update the data inside the csv file, but the things is every time I re-run it, it duplicates data Commented Feb 17, 2017 at 16:50

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.