user2890719 user2890719 - 1 month ago 10
C# Question

How to open text file and change text per paragraph?

I want to read a text file, and then add text before and after the existing text for every paragraph(text row). The text before and after changes after every paragraph, but repeats after every third one. The original text is always unique for every text row.

Ex: "1text" -> "Some text 1text Some text". "2text" ->"Some other text 2text Some other text
". "3text" -> " no idea 3text no idea ". "4text" -> " Some text
4text Some text"

Then replace the textfile with the new one, or create a new one.

Is this something I can build from?

static void Main(string[] args)
{
string[] lines = { "First line", "Second line", "Third line" };

System.IO.File.WriteAllLines(@"C:\Desktop\TestFolder\WriteLines.txt", lines);

using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Desktop\TestFolder\WriteLines.txt"))
{
foreach (string line in lines)
{
if (!line.Contains("Second"))
{
file.WriteLine(line);
}
}
}
}

Answer

This may be something you want, as I understood your intensions correctly:

static void Main(string[] args)
    {
        string readLine;
        string[] lines = { "First line", "Second line", "Third line" };
        int linecounter = 0;
        System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Temp\inputtest.txt");
        System.IO.StreamWriter outputfile = new System.IO.StreamWriter(@"C:\Desktop\TestFolder\WriteLines.txt");
        while ((readLine = file.ReadLine()) != null)
        {    
                outputfile.WriteLine(lines[linecounter] + readLine + lines[linecounter]);
                linecounter++;
                if (linecounter == 3)
                {
                    linecounter = 0;
                }
        }
        file.Close();
        outputfile.Close();
    }
Comments