Search code examples
c#textfile-ioread-write

C# - How to Append a set of iterating text lines to a text line in a certain line?


I need to append a set of iterating text lines to an already existing text file. How can i implement it using c#.

As an example-

Iterating text :

foreach (string toolName in value.Tools)
{
     sw.WriteLine("[\"at" + Count.ToString("D4") + "\"] = < ");
     sw.WriteLine("text = < \"" + toolName + "\" >");
     sw.WriteLine("description = <\" * \">");
     sw.WriteLine(">");
     Count++;
}

Should append it to the line 62 of myTextFile.txt


Solution

  • Something like this. Add all your contents into a list of strings and then output to a file.

    List<string> tools = new List<string>()
    {
        "Hammer", "Wrench", "Screwdriver", "etc"
    };
    
    List<string> output = new List<string>();
    int count = 1;
    foreach ( string toolName in tools )
    {
        if (output.Count ==  61)
        {
            output.Add ( "some string" );
            count++;
            continue;
        }
        output.Add ( "[\"at" + count.ToString ( "D4" ) + "\"] = < " );
        output.Add ( "[\"at" + count.ToString ( "D4" ) + "\"] = < " );
        output.Add ( "text = < \"" + toolName + "\" >" );
        output.Add ( "description = <\" * \">" );
        output.Add ( ">" );
        count++;
    }
    
    string path = @"C:\output.txt";
    File.WriteAllLines ( path , output.ToArray ( ) );