2

I am reading, then writing to a text file. I do this in multiple parts of my program. After I'm done writing, I always close it (I use streamreader/writer). There is usually about 3 seconds between the close and the next time it's opened.

However, the second time I need to write to the same file, I always get an access denied error because another process is using it. At no point is any other process ever using it, and restarting my program lets me read from it.

This is the open/write/close code:

System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileLocation.Text); file.WriteLine(account); file.Close(); 

3 Answers 3

7

Assuming there is no multi-threading then the issue is with proper disposal. The correct way to dispose of a stream or in general types that implement IDisposable is to wrap them in a using statement. The using statement ensures proper disposal and uses a finally block to ensure that the stream is closed even in exceptional circumstances.

using(var file = new System.IO.StreamWriter(saveFileLocation.Text)) { //do work... file.WriteLine(account); }//when file goes out of scope it will close 

Do this for all your streams.

Sign up to request clarification or add additional context in comments.

Comments

2

use using statement or try{ }finally{ file.Close(); }

Comments

1

Are you sure an exception isn't being thrown, preventing close from being called? Either way this is better code:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileLocation.Text)) { file.WriteLine(account); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.