# [.net] How to correctly read and append to files in C#?

This topic is 3399 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am trying to create a file and read from it in the same program (like a word processor proggy and without arrays) in C#. However I get exceptions saying that the file is already used by another proccess, when I try to write to it after I have already read it. I guess I just need the correct way to close the file so I can edit it or read it without exiting the program. Also if I close the file by calling the Flush() and Close() methods it throws an exception saying that you can't access a closed file, when I try to write to it again without exiting. Looked all over google but still can't figure this out. Thanks

##### Share on other sites
Rather than trying to open the same file multiple times, why not try sharing a single open Stream instance?

##### Share on other sites
The using-statement guarantees that the file is closed no matter what happens, even if an exception occurs:
using(var Stream = new System.IO.FileStream("File.ext", System.IO.FileMode.Create, System.IO.FileAccess.Write)){	//TODO: Write stuff}using(var Stream = new System.IO.FileStream("File.ext", System.IO.FileMode.Open, System.IO.FileAccess.Read)){	//TODO: Read stuff}

##### Share on other sites
Quote:
 Original post by FlopidI am trying to create a file and read from it in the same program (like a word processor proggy and without arrays) in C#. However I get exceptions saying that the file is already used by another proccess, when I try to write to it after I have already read it.

How are you opening the file (StreamReader, FileOpen, etc.)? Let's see your open code block. It sounds like you're not setting the correct FileMode or FileAccess when opening. Just so I'm reading this right, you want to open a file, read from it and write to it in the same application? Does it contain text data or binary data?

##### Share on other sites
I am using the file stream to write to the file. By adding the using statements I was able to acomplish what I needed since it looks like they dispose of the file each time a method is run. I have another question though. Is it possible to use something like IDispose on the file stream and not use the using statements?

##### Share on other sites
You can call Dispose() manually, but you shouldn't unless you need the object to live longer than you can write a using-block for. using-blocks are safer. There is no way to make the Dispose() call more automatic than a using-block while at the same time maintaining deterministic invokation of said Dispose() call.

• 10
• 40
• 15
• 10
• 23