Friday, 30 June 2017

VB - Reading a Text Resource File Line by Line


I'm not a VB programmer, but recently I needed to build an interface between Oracle and an MDB file, so I had to start getting familiar with Visual Express Studio 2013. I've done a lot of LotusScript in the past so it wasn't a big problem, but some things have proved to be a struggle.

For today's problem, I wanted to store a text file (used as a template) and pragmatically create a new version of it with a new name. It felt like the best thing to do was store the file as a resource, but it wasn't immediately obvious how to do it.

Creating the Resource

You can add a resource to your project as a text file using the Resources section of your project Properties. It's quite simple to access it in your code, in the following way:-

myString = My.Resource.MyTextFile 

But, if you do this then you'll get the whole file as a long text string. I wanted to be able to read it in using StreamReader and write it out line by line. But text files are always treated in this special way, so my method won't work.

The answer is to trick VB into thinking it's opening a binary file (just give it a different extension).

I created my file called inprep.template and moved it into the projects resource folder.

I then dragged it into the Resources page to register it as a project resource.

My new file resource

The VB Code

Here's the code to read the file (one row at a time) and output it to a new file.

Dim template As New MemoryStream(My.Resources.inprep)
Dim file As System.IO.StreamWriter
Dim oRdr As StreamReader = New StreamReader(template)
   file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", False)
   Do While oRdr.Peek() >= 0
Catch ex As Exception
End Try

It's simple enough once you realise that you need to handle it as a binary file.