C
C#7mo ago
Thommy

String Append

I have the following code:
blablabla.1 {
row1.withCode
row2.withCode
row3.withCode
row4.withCode
}

blablabla.2 {
row1.withCode
row2.withCode
row3.withCode
row4.withCode
}

blablabla.3{
row1.withCode
row2.withCode
row3.withCode
row4.withCode
}
blablabla.1 {
row1.withCode
row2.withCode
row3.withCode
row4.withCode
}

blablabla.2 {
row1.withCode
row2.withCode
row3.withCode
row4.withCode
}

blablabla.3{
row1.withCode
row2.withCode
row3.withCode
row4.withCode
}
i read the lines with File.ReadAllLines in an index[i] and search for string "blablabla.2" this is found on line 100 (example) Now I would have to add a line after row2.withCode. Can someone help me with that?
4 Replies
JakenVeina
JakenVeina7mo ago
you're gonna need to clarify what is that code supposed to do? what file are you reading?
Thommy
Thommy7mo ago
File is an Textfile and the text in it should be changed and then saved again
Bobby
Bobby7mo ago
@Thommy
public static void Main()
{
string filePath = "path/to/your/file.txt";

try
{
string[] blablaContent = File.ReadAllLines(filePath);


string updatedContent = FindAndInsert(blablaContent, "blablabla.2", "row2.withCode","what ever text you want" )
// Write the updated content back to the file
File.WriteAllText(filePath, updatedContent);

Console.WriteLine("File content updated successfully.");
}
catch (IOException e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}

public static string FindAndInsert(string[] text, string searchSegmentText,string searchRowText, string insertText)
{
List<string> list = new List<string>();
bool foundSegment = false;
foreach (var line in text)
{
list.Add(line);
var lnText = line.Replace("{","").Trim();
if (lnText.Equals(searchSegmentText))
{
foundSegment = true;
}
if (foundSegment && line.Trim().Equals(searchRowText))
{
list.Add(insertText);
}
}

return string.Join("\n", list);

}
public static void Main()
{
string filePath = "path/to/your/file.txt";

try
{
string[] blablaContent = File.ReadAllLines(filePath);


string updatedContent = FindAndInsert(blablaContent, "blablabla.2", "row2.withCode","what ever text you want" )
// Write the updated content back to the file
File.WriteAllText(filePath, updatedContent);

Console.WriteLine("File content updated successfully.");
}
catch (IOException e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}

public static string FindAndInsert(string[] text, string searchSegmentText,string searchRowText, string insertText)
{
List<string> list = new List<string>();
bool foundSegment = false;
foreach (var line in text)
{
list.Add(line);
var lnText = line.Replace("{","").Trim();
if (lnText.Equals(searchSegmentText))
{
foundSegment = true;
}
if (foundSegment && line.Trim().Equals(searchRowText))
{
list.Add(insertText);
}
}

return string.Join("\n", list);

}
I hope this helps ...
Thommy
Thommy7mo ago
thats very perfect. thx