title: C# Using StreamWriter, append a string in a specific line
body: <p>I want to manipulate a file with C# and StreamReader/StreamWriter. Initially, I need to find some specific lines and then append a string after them. Using this code, I can locate the lines that I want to write after them.</p>
  <pre><code>            string[] targetValues = {&quot;firstTargetValue&quot;};
  
              List&lt;int&gt; nlines = new List&lt;int&gt;();
              string[] newValues = {&quot;firstNewValue&quot; };
  
              int j = 1; //1-based indexing
              StreamReader sr = new StreamReader(filepath);
              string line = sr.ReadLine();
  
              while (line != null)
              {
  
                  line = sr.ReadLine();
                  j++;
  
                  if (line == targetValues[0])
                  {
                      nlines.Add(j);
                  }
              } 
              sr.Close();
  </code></pre>
  <p>So right now I am having the line number ( j=5 ). For the last part, I want to write my string after this line and not at the end of the file.</p>
  <pre><code>            var sw = new StreamWriter(filepath,true);
  
              sw.WriteLine(newValues[0]);
              sw.Close();
  </code></pre>
  <p>Can I somehow use the j that has the line number and achieve my goal?</p>
  <p>Text example:</p>
  <p><strong>Initial File</strong></p>
  <pre><code>1
  2
  3
  4
  firstTargetValue
  6
  7
  8
  </code></pre>
  <p><strong>Desired file</strong></p>
  <pre><code>1
  2
  3
  4
  firstTargetValue
  firstNewValue
  6
  7
  8
  </code></pre>
  <p>Thanks in advance, I was not able to find an answer that fits me</p>