C# - 如何将一组迭代文本行附加到特定行中的文本行?

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

我需要将一组迭代文本行附加到一个已经存在的文本文件中。我如何使用 C# 实现它。

举个例子-

迭代文本:

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

应将其附加到 myTextFile.txt

的第 62 行

如果我理解你在这个问题的模棱两可之间,也许你想要这样的东西

var lines = File.ReadAllLines(path).ToList();
lines.Insert(62,someFunkyText);
File.WriteAllLines(path,lines);

ReadAllLines(String)

Opens a text file, reads all lines of the file, and then closes the file.

List.Insert(Int32, T) Method

Inserts an element into the List at the specified index.

WriteAllLines(String, IEnumerable)

Creates a new file, writes a collection of strings to the file, and then closes the 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 ( ) );