safely open file for reading...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • !NoItAll
    Contributor
    • May 2006
    • 297

    #1

    safely open file for reading...

    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:

    Code:
    Dim FS As IO.FileStream = Nothing
    '... other code here...
    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!

    Des
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    The correct way to do this is as follows...

    Code:
    Try
        Using fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
            Using sr As New StreamReader(fs)
              'do stuff here
            End Using
        End Using
    Catch ex As IOException
        MessageBox.Show(ex.Message & vbCrLf & ex.StackTrace)
    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.

    Aimee
    Last edited by Aimee Bailey; Aug 10 '10, 06:27 PM. Reason: Force of habbit, accidently wrote it in C#!!!!!!!!!

    Comment

    Working...