By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,451 Members | 994 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,451 IT Pros & Developers. It's quick & easy.

safely open file for reading...

P: 296
I'm confused a bit. I need to open a file that another program regular reads and writes. I want to make sure that I open the program in such a way that it will not harm the other programs access in any way. My program can handle any errors created by the other program changing the file out from under me - I just need to make sure that when I open the file the other program can continue to read, write, delete, etc without even knowing about my program.
FYI this is simply a weather application where the "other" program is updating a table file with current weather data - my program reads that data and sends it to another application...

Here is the code I am using:

Expand|Select|Wrap|Line Numbers
  1. Dim FS As IO.FileStream = Nothing
  2. '... other code here...
  3. FS = New IO.FileStream(sPath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite Or IO.FileShare.Delete Or IO.FileShare.Read Or IO.FileShare.Write)
So my confusion is if the flags are granting the stated access to other applications, or if they are taking the access for my program. I only need to read - but somewhere along the line I believe I found that these flags are for the access levels I want to grant to other programs.
Any help would be appreciated!

Aug 2 '10 #1
Share this Question
Share on Google+
1 Reply

Aimee Bailey
Expert 100+
P: 197
The correct way to do this is as follows...

Expand|Select|Wrap|Line Numbers
  1. Try
  2.     Using fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
  3.         Using sr As New StreamReader(fs)
  4.           'do stuff here
  5.         End Using
  6.     End Using
  7. Catch ex As IOException
  8.     MessageBox.Show(ex.Message & vbCrLf & ex.StackTrace)
  9. End Try
When accessing files that other programs access, we need to specify both the mode and access methods so that windows is satisfied that we won't try to modify the stream. Also i always reccomend using's as they make sure to dispose of things properly.

Also, the FileAccess only needs to specify the rights your stream has in particular.

Aug 10 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.