Question Accessing a text file for reading and writing at the same time..

kill4

Member
Joined
Mar 1, 2011
Messages
5
Programming Experience
Beginner
(First off all hi to everyone my first post!)

Need some guidance..

Ok, i have two programs one program writes to a text file on a consistent basis, while the second program is opening this text file on a consistent basis for reading..

Sometimes the programs are accessing the file at the same time and the user keeps getting this error : this process cannot access the file because its already in use..

Is there any class, in system.io that i can use to modify the settings of this text file so both programs can access it at the same time?

Any help would be appreciated!
 
When you open a FileStream you can specify FileShare options, default setting allow subsequent read access. For text files you would commonly wrap a StreamWriter/Reader around such a stream for convenient writes/reads, but you can also create these objects directly without opening the FileStream first. Both these classes constructors where you specify a path opens a FileStream with FileShare.Read, ie a StreamReader will be allowed when a StreamWriter uses the file, but a StreamWriter will not be allowed when a StreamReader uses the file (but another reader will).
So, if you want to open a file for reading, and allow subsequent both writers/readers, you must use the FileStream with FileShare.ReadWrite and read that with a StreamReader.
These classes are found in System.IO Namespace ()
 

Latest posts

Back
Top