C
C#15mo ago
Clara

❔ 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
Pobiega
Pobiega15mo ago
You don't show where the first block of code runs But that using stream reader must dispose to release it's file handle
Clara
ClaraOP15mo ago
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"?
Pobiega
Pobiega15mo ago
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 happens
Clara
ClaraOP15mo ago
So in other words I need to package the using StreamReader into a method and my problem is solved?
Pobiega
Pobiega15mo ago
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
Clara
ClaraOP15mo ago
I'll read up on that in the morning. For now, my code runs, thanks to you! Cheers!
ero
ero15mo ago
(at the end of the scope)
Pobiega
Pobiega15mo ago
Wouldn't you know it, the end of the method scope is.... At the end of the method. Wow!
Azrael
Azrael15mo ago
😱
ero
ero15mo ago
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
Accord
Accord15mo ago
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.
Want results from more Discord servers?
Add your server