Search code examples
c#appendstringreader

Append Text with StringReader (After reader.ReadLine())


Right now I'm building a game application using c#, which will require loading from text file for the game script. (It's quite a simple visual novel game)

Now when the main form loads, i load the script from the file script.txt And i declared :

StringReader reader = new StringReader(script);

as a global variable there

Now in the middle of the game where the reader is in the middle of the string script, I need to append starting from next line of the reader. Basically what I want to achieve:

Append all texts from "news.txt" to script starting from reader.ReadLine() [i.e. in the middle of the string script]

What will be the most efficient solution to achieve this?

What I know:

StreamReader sr = new StreamReader("news.txt");
string news = sr.ReadToEnd();
//Now how to append 'news' to reader.ReadLine() ??

Edit for more clarification (sorry, this is my first time asking here) : I will try to explain more about what i'm trying to achieve here. What i'm having right now :

//global variables
string script;
StringReader reader;

//during form_load
StreamReader sr = new StreamReader("script.txt");
script = sr.ReadToEnd();
reader - new StringReader(script);

//And as the game progresses, I keep on implementing reader.ReadLine()..
//At one point, the program will ask the user, do you want to watch the news?
DialogResult dialogResult = MessageBox("Do you want to watch the news?", , MessageBoxButtons.YesNo

if(dialogResult == DialogResult.Yes)
{
   StreamReader newsSr = new StreamReader("news.txt");
   string news = newsSr.ReadToEnd();
   //now I want to append the contents of 'news' to the string 'script' after reader.ReadLine() - any best way to implement this?
}

One possible way (and i think it's the worst way as well) is by introducing one count variable, to get the starting position of the last reader.ReadLine(), and execute the desired result using Insert like follows : script = script.Insert(startIndex, news)


Solution

  • in the end I was able to resolve this problem. This is what I used (in case anyone wanna know :))

    //I'm using a switch statement, in case reader.ReadLine() == "#(morningnews)"
    dialogResult = MessageBox.Show("Do you want to watch the news?", , MessageBoxButtons.YesNo);
    if(dialogResult = DialogResult.Yes)
    {
      StreamReader sr = new StreamReader(directoryName + "\\morningactivities\\morningnews1.txt");
      string news = sr.ReadToEnd();
      script = script.Replace("#(morningnews)", "#(morningnews)\n" + news);
      reader = new StringReader(script);
      while (reader.ReadLine() != "#(morningnews)")
        continue;
      loadNextScript();
    }
    

    Thanks for everyone who helped, it gave me the inspiration to actually came up with this.