Crapter 9: File Management |
Top Previous Next |
9.1 Text FilesIn 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
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
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
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.
|