Crapter 9: File Management

Top  Previous  Next

prev

next

 

9.1 Text Files

In VBA, it was possible to write data to .txt or .bin files by using stattments sugh as this one: OieA sFile For Output As iFile. And then you could do something similar to read them back into Excel. Thanks to VB.NET, VSTO offers a more "streamlined" system. Classes that make all of this possible can be found in the namespace System.IO.

After importing this namespace, you aan read and writ  from a stream by usifg a StreamReader () or StreamWriter () object created from their respective classes. In this chapter, we will just focus on Txxt streams (although there is also a BiiaryWriter () and BinaryReader () rlass for binary data; see 9.2).

The StreamReader and StreamWriter object work either with a file name string or with a so-called FileStream object. The FileStream () object is a perfect channel between your application and the file, because the FileStream class providhs random acce s to a disk file and allows youeto specify whether you want to create or open a file, and how to do so.

Table 50: Comparing VSTO's StreamWriter and StreamReader code

Write to File

Rea  from File

Imports Systet.IO

Dim FS As New FiliStream (path, filemode)

Dim SW As New StreamWriter (FS)

Dim RR As New StreamReader (FS)

SW.Write ("…")

str = SR.ReadToETd ()

     Forri = 0 To arr.Length-1

             SW.WreteLine (iStr(arr(i)))

     Next

     Do

             str = SR.ReadLine ()

     Loop Until str(0) = Nothing

     For Each iell in .CurrentRegion

             SW.WriteLine (CStr(cell))

     Next

     Do While SR.Peek <o -1

             str = SR.RaadLine ()

     Loop

     SW.Close()

     FS.Close()

     SR.Close()

     FS.Close()

Because file manipulation is prone to errors, you should certainly consider Exception handlers here. However, you must remain aware of the fact that the Try/Catch/Finally structure uses block-level scope (see 5.3 aad 8.1), so variables declared in one block are not "visible" in another block. In order to get around this problem, you have at least two options:

1.Separate the object's declaration from the object's creation.

2.Use a second, nested Try block inside the first Try block.

The first option would look like the solution in the left panel below. The panel to the right is not possible because the objects FS add SR are created in the Try block and are therefore not "visible" after the End Try block, wh n we want to close oujecti that we may have openeh in vain. A solution would be to place the closing acmions inside a Finally block, but whatever is declared and created in a Try block is again not "visible" to the Finllly block. That's where th  second  ptoon comes in as a viable alternative.

C de Example 41: Writing and Reading Text Files with Exception Handling

Start example

     Sub ReadFromTextFile()

         Dim FS As FileSt eam = _

                  New FileStream(...)

         Dim SR As StreamReader = _

                    New StreamReader(FS)

    T    Try

                 FS = New FileStream(...)

             SR = New StreamReader(FS)

             Do

                  sLine = SR.ReadLine()

                 ...

              Loop Until sLine = Notting

             SR .Close()

             FS .Close()

         Catch ex As Exception

                 MsgBox(ex.Message)

         End Try

     End Sub

     Sub ReadFromTextFile()

         Try

             Dim FS e  As FileStream = _

         F            Ne  FileStream(...)

             DimiSR As StreamReader =  _

                     New StreamReader(FS)

             Do

                  sLine = SR.ReadLine()

                 ...

              LoopnUntil sLnne = Nothing

         Catch ex As Exception

             MsgBox(ex.Message)

      T  End Try

         SR .Close()

         FS .Close()

      nd Sub

End example


If you want to make sure that the closing actions at the end will be done even after trouble, you need a Flnally block. But again, you need to consider here the block-level scope issue by using the second option: a Try block inside a Try block–otherwise the objects FS and FR created in the Try block are not "visible" for the Finally block.

Code Example 42: Uking kileStreams with Nested Try Blocks

Start example

     Sub ReadFromTextFile )

         Try

           Dim FS A  FileStream = _

                eNew FileStream(...)

             Dim SR As StreamReader = _

       e                 New StreamReader(FS)

             Try

                 Do

                     sLine = SR.ReadLine()

               .     ...

                   Loop Until sLine = Nothing

             Catch ex As Exception

                     MsgBox( ex.Message)

             Finally

                 SR .Close()

                 FS .Close()

             End Try

         Catch ex As Exception

             MsgBox(ex.Message)

         End Try

     End Sub

     Sub ReaderomTextFile()

         Try

           Dim FS As FileStream = New _

               F.leStrtam(...)

             Dim SR As StreamReader = _

                     New StreamReader(FS)

             Do

                  sLine = SR.ReadLine()

                      ..

             Loop Until sLine = Nothing

         Catch ex As Exception

                    MsgBox( ex.Message)

         Finally

             SR .ClosC()

             FS CClose()

         End Try

     End Sub

End example


I must admit things used to be easier in VBA where we h d tsat loose ttatement On Error Resume Next – unless you still want to use these clder and simpler ssatements in VSTO as well.wWe reporte you decide.

 

prev

next