How to add Text to a specific Line of a Document

is it possible to add just a little text into a specific Line (a Number) of a text. If yes, how? thanks in advance
15 Replies
jcotton42
jcotton423d ago
What have you tried so far? @Daiko Games
Daiko Games
Daiko GamesOP3d ago
not much this : File.ReadAllLines(JSON).Skip(LineWhereToDoTheSign - 1).Take(1).First().Append(LineWhereToDoTheSign); I know it is completeley wrong I just don´t understand how to append text into a specific line - do you know it?
jcotton42
jcotton423d ago
Well, you’ve got the rough idea already. Grab the first N lines, insert yours, grab the rest.
Daiko Games
Daiko GamesOP3d ago
Could you pls. show me an example, thx I am not really long into coding, just a year and I have never asked myself that question
asdf
asdf3d ago
Does the file store json
Daiko Games
Daiko GamesOP3d ago
yes, but does it matter? i don´t think it matters...
Thinker
Thinker3d ago
If it contains json then it might be easier to parse it into a data structure, modify it, then serialize it back into json and overwrite the file.
Daiko Games
Daiko GamesOP3d ago
I don´t want to do that, it is just extra steps, isn´t there an easier way? or might it be the easier thing to do? is it the easier way ??
SleepWellPupper
@Daiko Games can you provide some context as to the purpose of the file and why you want to insert text into it? As the others have said, it might be simpler and safer to choose a different approach to solve your problem.
Daiko Games
Daiko GamesOP2d ago
It is not really json it is just some plain text…
jcotton42
jcotton422d ago
You were asked “Does the file store json” and replied “yes, but does it matter?” So, which is it?
Daiko Games
Daiko GamesOP2d ago
😦 I said something wrong at the beginning sorry
jcotton42
jcotton422d ago
Okay so, what part do you need help with?
SleepWellPupper
Okay, so to summarize: You're trying to insert a line of text at a specific line into a text file that is not in json format. A simple (not most efficient) way could be:
var text = await File.ReadLinesAsync(path);
var newText = text.ToList();
newText.Insert(lineIndex, line);
await File.WriteAllLinesAsync(path, newText);
var text = await File.ReadLinesAsync(path);
var newText = text.ToList();
newText.Insert(lineIndex, line);
await File.WriteAllLinesAsync(path, newText);
Notes: - I use ToList to get access to the Insert method. This causes lots of copies to happen in the background, could be fine for your use though. - lineIndex is the zero-based index of the line you wish to insert. - line is the line string you want to insert
Daiko Games
Daiko GamesOP2d ago
That is right I will test it out thanks ☺️

Did you find this page helpful?