0

Beginner here, I'm having some troubles reading and writing to an existing .txt file. My overall goal is to receive strings containing equations (specified by numbers and +,-,*,/,(,) operators), running these equations through a calculator I built (see the Calculate method), and then writing the results to the same file. Say my file contains the following lines:

1+8

sin(90)+9

Then, I should write to that file, so it would look like this:

1+8 = 9

sin(90)+9 = 10

And so on.

Here's what I've got so far:

List<string> lines = new List<string>();
List<string> results = new List<string>();

foreach (string line in File.ReadLines(@"C:\Users\...\file.txt"))
{
   string result = Calculate(line).ToString();
}

Now I'm really not sure what to do. I've been trying using File.WriteAllLines and File.AppendText, but an error is thrown, and the current stream seems to be occupied.

Any suggestions? Thanks.

  • You need to close the read stream before you can write to same file. – jdweng Jul 10 '22 at 23:04
  • What error, where? – gunr2171 Jul 10 '22 at 23:14
  • Reading and writing a file in-place is far more difficult than you think. Any mistake or error can unrecoverably corrupt your file. You want to [write changes to a temporary file and, if it works, swap your original and temporary file](https://stackoverflow.com/a/65363888/22437) – Dour High Arch Jul 11 '22 at 00:30

1 Answers1

0

Switch from File.ReadLines to File.ReadAllLines.

Behind the scenes ReadLines uses Streams to read each line from the file as you request it. However, in order to do that, it needs to lock the file from other access. You can't write to the file you're currently reading from (ie. inside the foreach loop).

ReadAllLines loads all lines into memory. You are then free to overwrite the original file because you've already slurped up all the info you need.


As an alternate, you can continue working with ReadLines, just ensure you write your results to a different file.

gunr2171
  • 16,104
  • 25
  • 61
  • 88