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

Started by
4 comments, last by jpetrie 15 years, 2 months ago
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
Advertisement
Rather than trying to open the same file multiple times, why not try sharing a single open Stream instance?

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

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}
----------------------------------------MagosX.com
Quote:Original post by Flopid
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.


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?

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?
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.

This topic is closed to new replies.

Advertisement