使用 List 动态<string>写入文件:格式问题



我写了一个函数,可以让我动态地写一个包含一些代码的文件。我正在给方法输入点数。我已经搞定了,但我遇到了一个愚蠢的格式问题。

以下代码(带numberOfPoints = 3(

private static void PointsGenerator(int numberOfPoints)
{
string fileContent = Resources.Points_AutoGenerated;
List<string> lines = new List<string>(fileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
for (var j = 0; j < numberOfPoints - 1; j++)
{
int index = 0;
for (var i = 1; !lines[i].Equals("ENDMODULE"); i++)
{
if (lines[i].Contains("! <<< POINT PLACEHOLDER >>>"))
{
if (numberOfPoints == 1)
{
// Let's remove the placeholder...
lines.RemoveAt(i);
// ... and the extra new-line.
lines.RemoveAt(i);
}
else
{
lines.RemoveAt(i);
lines.Insert(i, Resources.Snippet_POINT);
index = i;
}
}
}
if (j < numberOfPoints - 2)
{
lines.Insert(index + 2, "! <<< POINT PLACEHOLDER >>>");
}
}
Console.WriteLine(string.Join(Environment.NewLine, lines.ToArray()));
}

正在输出此文件

! <<< Code generated with MG ABB Missions Generator. >>>
MODULE Points_AutoGenerated
TASK PERS robtarget pPointX := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
ENDMODULE

我不喜欢它,因为我在ENDMODULE行之前错过了一个额外的换行符。

但是如果我使用第二个代码(只是粘贴我更改的部分(

if (j < numberOfPoints - 2)
{
lines.Insert(index + 2, "! <<< POINT PLACEHOLDER >>>");
}
else
{
lines.Insert(index + 1, Environment.NewLine);
}

相反,我得到了这个输出

! <<< Code generated with MG ABB Missions Generator. >>>
MODULE Points_AutoGenerated
TASK PERS robtarget pPointX := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

ENDMODULE

与以前类似,我不喜欢,因为末尾有额外的换行符(我只想要其中之一!

我错过了什么?

这是我用来生成最终文件的两个模板:

Points_AutoGenerated.txt

! <<< Code generated with MG ABB Missions Generator. >>>
MODULE Points_AutoGenerated
TASK PERS robtarget pPointX := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
! <<< POINT PLACEHOLDER >>>
ENDMODULE

Snippet_POINT.txt

TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

只需添加一个空字符串,您已经从 WriteLine(Join((( 中获得了换行符。

else
{
lines.Insert(index + 1, "");
}
// here the empty string becomes an empty line
Console.WriteLine(string.Join(Environment.NewLine, lines.ToArray()));

最新更新