FileShare.Read error ?

G

GB

Hi Everybody!

I have 2 different processes/application. One is writing to a file and
another is reading from it. For some reason the code doesnt seems to
work and gives mscorlib.dll IOException error "This file is being used
by another process".
Both the applications are in C#.

P.S. Even if I try to open the file with NotePad (while my server is
writing data in the file)it gives the same error.

Here's the code esnippet :

Writing the Buffer
********************
FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate,
FileAccess.Write, System.IO.FileShare.Read);

StreamWriter sw = new StreamWriter(fs);
sw.Write(buff, 0, buff.GetLength(0)); // no. of bytes to write

Reading the Buffer
*********************
string FileName = "D:\\dataFile.txt";
StreamReader sr = new StreamReader(new
FileStream(FileName,FileMode.Open,FileAccess.Read));

int TotalBytesRead = 0;


int retval = sr.ReadBlock(mapBuff, 0, mapBuff.GetLength(0)); //bytes

if(retval > 0)
{
TotalBytesRead = TotalBytesRead + retval;

}

Thread.Sleep(50);


Can anybody point out whats the error ? or is it a BUG ?

Thanks a lot for the help,
Gaurav
 
B

Ben Dewey

Make sure you call the Stream.Close() method when you are finished reading
and writing.
 
S

Stephen Martin

When you open your stream for writing you are opening it with a file share
setting of Read. This means that trying to open it in Notepad (which is
trying to open it for reading and writing) will fail. Also, when you open
your reader stream you are using the default file share setting of Read.
This means that if your writer stream is already open for writing the
attempt to open the reader stream will fail since a handle with the
FileShare.Read setting cannot be acquired. Conversely, if your writer stream
is not open then the reader stream will open successfully but any subsequent
attempt to open the writer stream will fail.

You'll need to change this:

StreamReader sr = new StreamReader(new
FileStream(FileName,FileMode.Open,FileAccess.Read));

to

StreamReader sr = new StreamReader(new
FileStream(FileName,FileMode.Open,FileAccess.Read,FileShare.ReadWrite));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top