Search code examples
c#for-looptext

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.


Solution

  • 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.