0

I've been trying to write new texts in a specific line without completely overwriting the current contents of the file, but I can't seem to make it work. For example, in my file called Test.txt. This is what's currently written in it:

1
2
3
4

8
9
10

As you may have noticed, I did not include the numbers 5,6 and 7. There is also a space where you can insert 5,6 and 7. But as I tried to insert those numbers, it's giving me this output:

1
2
3
4

8
9
101
2
3
4

5
6
7

It clearly have added a bunch of numbers that I did not want. Code for this is indicated below. Hope you guys can help me on this one.

namespace TestCode
{
class Program2
{
    static void Main()
    {
        var lines =   System.IO.File.ReadAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt");
        lines[5] = "5";
        lines[6] = "6";
        lines[7] = "7";
        System.IO.File.AppendAllLines(@"C:\Users\User1\Documents\Visual    Studio 2015\WebSites\MusicStore\Pages\Test.txt", lines);
    }
  }
}
zx485
  • 28,498
  • 28
  • 50
  • 59
BrunoEarth
  • 333
  • 2
  • 5
  • 16
  • 1
    Use `WriteAllLines` instead of `AppendAllLines` – Tim Schmelter Jan 26 '17 at 12:56
  • You are also overwriting the last three elements (8, 9, 10) in your array... – rory.ap Jan 26 '17 at 12:58
  • when u use `AppendAllLines` all data in `lines` will append data in file – MKasprzyk Jan 26 '17 at 12:58
  • @TimSchmelter - I already tried changing it to WriteAllLines but its still overwriting 8,9 and 10. I hope some of you guys can show actual examples. I'm really still a beginner in coding. – BrunoEarth Jan 27 '17 at 13:46
  • It makes me wonder why this question was considered duplicate. The recommended answer above doesn't even have the same output that I want to achieve. Adding a new line is different from inserting text in a specific line without overwriting it. – BrunoEarth Jan 27 '17 at 13:54
  • If the answer above is not working for me, then it is not a duplicate because if it is, the above question should exactly solve my question. – BrunoEarth Jan 27 '17 at 13:56

0 Answers0