Need expert's advice

P

PJ

Hi all,

I have two option to open a file stream

1. Dim mStream As Stream = New FileStream(localFile, FileMode.Open,
FileAccess.Read)

This works fine as long as the file is closed. If a file is being opened by
another process (even a .log or .txt file), it fails.

2. Dim mStream As Stream = File.Open(localFile, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite)

This works fine as long as the file is closed. However, if the file is .txt
or .log, it works fine EVEN IF the file is open (Failed when I used option
1)

My question is, can I use option 2 or I have to use option 1 for this? What
are the differences? Thanks. I use in my FTP class.
 
C

Chris Dunaway

The difference is the FileShare parameter. In your first line you did
not allow sharing and you are basically saying:

"I want to open the file for Read access and I DONT want to allow
anyone else to open it or even access it"

Since another process has already opened the file, you cannot get
exclusive access to it so the call fails.

For the second you are saying this:

"I want to open the file for read access but I will allow other
processes to Read and Write to the file."

Since you allow the other process ReadWrite access, your call was
successful because you were not trying to get exclusive access to the
file. If the other process had opened the file exclusively, then your
call would still have failed.
 

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

Top