C# StreamWriter: Create Multiple Text Files

In C#, you can utilize the StreamWriter class to create and write to text files. To create multiple text files, you can instantiate the StreamWriter class multiple times in a loop. Below is an example code demonstrating how to create multiple text documents using StreamWriter.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            string fileName = $"file{i}.txt";
            using (StreamWriter writer = new StreamWriter(fileName))
            {
                writer.WriteLine($"This is file {i}");
            }
            Console.WriteLine($"File {fileName} created.");
        }
    }
}

In the example above, the program will create 5 text files (file1.txt to file5.txt) within a loop, each file containing a line of text (“This is file {i}”). Lastly, the program will print a message on the console for each file created.

I hope this helps you! Feel free to ask me if you have any questions.

bannerAds