❔ StreamReader and File.WriteAllText are stepping on each others toes.
I'm currently writing what I thought was a pretty straightforward piece of code. First I read a bunch of data from a file into a list using StreamReader and when I've done all my edits, I overwrite the contents of the file using File.WriteAllText. See appended images.
However, I'm currently getting an exception when the code hits the File.WriteAllText line telling me that it can't access the file, because it is already in use by another process. What am I not seeing here? Would really appreciate the help!
11 Replies
You don't show where the first block of code runs
But that using stream reader must dispose to release it's file handle
The first block of code just runs in Main, or Program or whatever you want to call it.
What do you mean by "dispose to release it's file handle"?
Aah
That's why
So what
using
does is add the Dispose
call at the end of the method
If that's in main, that never happensSo in other words I need to package the
using StreamReader
into a method and my problem is solved?That, or use the alternative syntax for using, give it a body
With {}
Then it disposes at the closing bracket, instead of end of method
I'll read up on that in the morning. For now, my code runs, thanks to you! Cheers!
(at the end of the scope)
Wouldn't you know it, the end of the method scope is.... At the end of the method. Wow!
😱
I mean you don't necessarily know the code isn't in some if statement
Maybe a try-catch
Also what a stupid reply lol
I was just letting the OP know what's technically correct
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.