Reputation:
In a for each loop I am currently adding to my file like this:
using (StreamWriter sw = File.AppendText(path))
{
StringBuilder builder = new StringBuilder();
builder.Append(LastName.Trim()).Append("\t");
// more stuff
But every time that user runs the program I want that file to be created from scratch. Currently it is creating the file if it does not exists - which is good - but it is also appending to the end of the previously created file.
Upvotes: 0
Views: 1742
Reputation: 68440
You could use TextWriter
// Create file a single time
using (TextWriter writer = File.CreateText(path))
{
for (int i = 0; i < iterations; i++)
{
// Add content to the file inside the loop
writer.Write(LastName.Trim());
//etc...
}
}
Upvotes: 1
Reputation: 12633
You are using File.AppendText
- what did you expect?
If you want to override the file on each run, use File.Create
instead.
Upvotes: 3
Reputation: 1007
Instead of using (StreamWriter sw = File.AppendText(path))
Try using (StreamWriter sw = new StreamWriter("fileName.txt"))
You are appending instead of creating something new / overwriting what is there.
Upvotes: 1
Reputation: 1870
You could create a Tempfile with:
and store all filenames in one central file that does not change.
Upvotes: 2