File access

  • Thread starter Thread starter Magnus Blomberg
  • Start date Start date
M

Magnus Blomberg

Hello!

I am trying to use a StreamReader to read a file that is in use, but get an
error message that the file is being used by another process.
It is nothing strange with the error message, cause the file is in use, but
when using Notepad, I can read the file, so I think there should be a way to
do this from .Net code as well?!?!

Any ideas?
/Magnus
 
If you open the file using FileStream.Open instead of using StreamReader, you
can specify how to share the file with other users of the file (using the
FileShare enumeration). If you still want to use StreamReader, you can
create a StreamReader from the FileStream returned by FileStream.Open.

HTH, Jakob.
 
Hello!

Tanks for your answer. Unfortunately I get the same message using the
code row below:

FileStream fs = File.Open(myfile, FileMode.Open,
FileAccess.Read, FileShare.Read);

Any idea?

Regards Magnus
 
Hey Magnus,

I tried opening the same file for reading (using Filestream) from several
processes using FileShare.Read without any problems. Are some of your
processes writing to the file or are all of them opening the file for reading
only using your line of code below? Are you getting an exception every time
you run your program or only sometimes?

Regards, Jakob.
http://www.dotninjas.dk
 
Hello!

I think I solved the problem by using:

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

Best Regards Magnus
 
Back
Top