c#:在文本文件的两行之间追加文本



我有以下文本文件:

TOP:
BOTTOM:

我想在这些行之间添加字符串,并添加换行符。我该怎么做呢?

添加

后的最终结果应该是:
TOP:
<newaddedstring1>
<newaddedstring2>
<etc...>
BOTTOM:

更新:新代码似乎可以工作:

public class Program
{
public static void Main()
{
string filename = @"/test.txt"; //File provided as dummy
string location = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + filename; //Full Directory path will be in the same folder as the project
List<string> data = File.ReadAllLines(location).ToList(); //Convert data to list
List<string> rt = InjectAndPrint(data);
File.WriteAllLines(location, rt);

}
static List<string> InjectAndPrint(List<string> textToSearch)
{
string windex = "Windows:";
string lindex = "Linux:";
string winiplist = "127.0.0.1,127.0.0.2,127.0.0.3,127.0.0.4,127.0.0.5,127.0.0.6,127.0.0.7,127.0.0.8,127.0.0.9,127.0.0.10,127.0.0.0";
string liniplist = "192.168.74.133,192.168.74.118,192.168.74.155";
List<string> winip = winiplist.Split(',').ToList<string>();
List<string> linip = liniplist.Split(',').ToList<string>();
List<string> arr = textToSearch;
Parallel.ForEach(winip, text => {
arr.Insert(arr.IndexOf(windex) + 1, text);
});
Parallel.ForEach(linip, text => {
arr.Insert(arr.IndexOf(lindex) + 1, text);
});
return arr;
}
}

您不需要使用SkipWhile()TakeWhile()。只需搜索BOTTOM:并插入您的行(或搜索TOP:)索引+ 1,插入:

static List<string> InjectAndReturn(
string textToSearch,
string searchTerm,
string textToInject)
{
var arr = textToSearch.Split('n').ToList();
arr.Insert(arr.IndexOf(searchTerm), textToInject);
return arr;
}
var data = "TOP:nBOTTOM:";
var rt = InjectAndReturn(data, "BOTTOM:", "<New Line>");

rt.ForEach(x =>
{
Console.WriteLine(x);
});

DotNet小提琴

最新更新