HanH1113
HanH1113

Reputation: 209

C# for loop to write line by line

I am trying to write one line of text 75 times and increase the number by 1 till it hits the 75 condition. Starting at 2 for a reason. Here's the code

class WriteTextFile
{
    static void Main()
    {
        string path = "C:\\Users\\Writefile\\test.txt";
        string line;
        int i = 2;

        while (i <= 75 )
        {
            line = "Error_Flag = 'FOR_IMPORT' and location_type =   'Home' and batch_num = " + i + "\n";
            System.IO.File.WriteAllText(@path, line);
            i++;
        }
    }
}

With this, it just writes one line with 75 at the end. I want it to write all 74 lines with the same thing, only the number goes up every time. Thanks.

Upvotes: 7

Views: 19323

Answers (3)

Andrew
Andrew

Reputation: 5093

System.IO.File.WriteAllText will overwrite the contents of the file each time.

What you probably should do is use a StreamWriter:

using (var sw = new System.IO.StreamWriter(path))
{
    for (var i = 2; i <= 75; i++)
    {
        sw.WriteLine("Error_Flag = 'FOR_IMPORT' and location_type =   'Home' and batch_num = {0}", i);
    }
}

This will automatically create the file, write all the lines, and then close it for you when it's done.

Upvotes: 11

user932887
user932887

Reputation:

You're overwriting the file on each new write operation. Consider appending to it.

Upvotes: 0

JNYRanger
JNYRanger

Reputation: 7097

Don't use File.WriteAllText because this generates a new file every time.

Instead try something like this:

using (var writer = new StreamWriter("filename.txt"))
{
    for(int x = 2; x <= 75; x++)
    {
        writer.WriteLine("Error_Flag = 'FOR_IMPORT' and location_type =  'Home' and batch_num = " + x);
    }
}

Upvotes: 4

Related Questions