FileStream in VB.net

I have some questions regarding the code below:

Dim sdirectory as string="C:\vb.net\files"
dim sfile as string="example.txt"
dim spath as string= sdirectory & sfile
dim sfilestrean as filestream
sfilestream=new filestream(spath,filemode.open,fileaccess.readwrite)


1-can I just use: dim spath as string="C:\vb.net\files\example.txt" instead of declaring Dim sdirectory as string="C:\vb.net\files"  then dim sfile as string="example.txt"?

2-when I put filemode.open, Fileaccess.write or Fileaccess.readwrite or Fileaccess.read or Fileaccess.none.   Does this mean if that file exists and accesseb by another user while this code is running can allow/prevent that user from read or write? please explain.


3- when I put filemode.createnew, Fileaccess.write or Fileaccess.readwrite or Fileaccess.read or Fileaccess.none.   Does this mean if that file exists and accesseb by another user while this code is running can allow/prevent that user from read or write? please explain.

Thanks

jskfanAsked:
Who is Participating?
 
nayernaguibConnect With a Mentor Commented:
1. Of course you can! Afterall, you never use any of the strings alone, but rather, use the concatenated version. Variable names do not make any difference.

2. This depends upon how you want to access the file. You can have as many users/applications open the same file simultaneously for reading. However, a user/application that opens a file for writing prevents access to the file as long as it is open. Similarly, if a file is already open for reading, you cannot open it for writing.

3. Logically, you cannot create a file for reading, the file will simply be empty!! Since you can only open a file using FileMode.CreateNew for *writing*, therefore no one else would be able to open the file as long as it is open by your application.

_______________

  Nayer Naguib
0
 
jskfanAuthor Commented:
If a user runs the application that has:
 filemode.open, Fileaccess.write

and the file was already open by another user for reading or writing , what would heappen?
0
 
nayernaguibConnect With a Mentor Commented:
The application would throw an IOException that contains the following message:

"The process cannot access the file 'xyz.xyz' because it is being used by another process.", where xyz.xyz is the file that was already open.

Therefore you should enclose the above statement within a Try/Catch block, as in the following example:

        Dim fs As System.IO.FileStream
        Try
            fs = New System.IO.FileStream("e:\xyz.txt", IO.FileMode.Open, IO.FileAccess.Write)
        Catch ex As System.IO.IOException
            MessageBox.Show(ex.Message)
        End Try

_______________

  Nayer Naguib
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.