'C#: Append text to text file between two lines
I have in a txt file the following:
TOP:
BOTTOM:
I want to add between those lines strings adding also a newline. How can I do this?
The end Result should be this after adding:
TOP:
<newaddedstring1>
<newaddedstring2>
<etc...>
BOTTOM:
UPDATE: THE NEW CODE WHICH SEEMS TO WORK:
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;
}
}
Solution 1:[1]
You don't need to use SkipWhile()
or TakeWhile()
. Just simply search the BOTTOM: and insert your line (Or search the TOP: index + 1 and insert:
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mohi |