0

I'm wondering if there is a way to write data from the program to a specific line on an external text document.

For example, so far within my program I have a string array which gets the users input and saves it in the corresponding element and into the text file. It can read the first element fine, however how do I get it so when I enter the input for element 2 it overwrites what is on line 2 so when it reads the text file it displays the newest input into a label?

  • is the text document in question formatted in a particular way that would make the line easily identifiable? Also can we see code for what you've done so far? If it's not easily identifiable, it should be a simple for loop with a counter, if it is, then just loop through the document line by line until you run into your identifier. Also, check the linked answers, as this question is marked as duplicate. – user2366842 Jun 22 '15 at 18:26

1 Answers1

1

Well, the simplest approach would be:

string[] lines = File.ReadAllLines(path);
lines[index] = newText;
File.WriteAllLines(path, lines);

However, that assumes that there's already an appropriate number of lines in the file - is that always the case?

Note that this is also potentially inefficient in memory if the file is very large - but making it more efficient would also make the code more complicated.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That's great, thank you! Yes there is a fixed amount of lines and i'm not that worried about the memory size to be honest however I will keep that in mind for future programs, thanks again! – Rhys Kendall Jun 23 '15 at 22:15