user2740190
user2740190

Reputation:

Creating a new file each time program runs

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

Answers (4)

Claudio Redi
Claudio Redi

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

Idan Arye
Idan Arye

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

tyh
tyh

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

Venson
Venson

Reputation: 1870

You could create a Tempfile with:

Path.GetTempFileName()

and store all filenames in one central file that does not change.

Upvotes: 2

Related Questions